def test_encrypt_decrypt(self): key = jwe.kdf(b"Testing", b"Pepper") data = b"Just some data" encrypted = jwe.encrypt(data, key) assert encrypted != data assert jwe.decrypt(encrypted, key) == data
def build_payload(self, bundle, view_only=None, cookie=None): query_params = {} if cookie: bundle['cookie'] = cookie if view_only: # View only must go outside of the jwt query_params['view_only'] = view_only raw_payload = jwe.encrypt( jwt.encode( { 'data': bundle, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION) }, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM), JWE_KEY) # Note: `aiohttp3` uses `yarl` which only supports string parameters query_params['payload'] = raw_payload.decode("utf-8") return query_params
def get_db_prep_value(self, input_json, **kwargs): if not input_json: return None input_json = self.prefix + jwe.encrypt(json.dumps(input_json).encode('utf-8'), settings.SENSITIVE_DATA_KEY) return input_json
def make_payload(institution, username, fullname='Fake User', given_name='', family_name=''): data = { 'provider': { 'id': institution._id, 'user': { 'middleNames': '', 'familyName': family_name, 'givenName': given_name, 'fullname': fullname, 'suffix': '', 'username': username } } } return jwe.encrypt( jwt.encode({ 'sub': username, 'data': json.dumps(data) }, settings.JWT_SECRET, algorithm='HS256'), settings.JWE_SECRET)
def test_encrypt_decrypt(self): key = jwe.kdf(b'Testing', b'Pepper') data = b'Just some data' encrypted = jwe.encrypt(data, key) assert encrypted != data assert jwe.decrypt(encrypted, key) == data
def build_url(self, **kwargs): options = {'payload': jwe.encrypt(jwt.encode({'data': dict(dict( action='download', nid=self.node._id, provider=self.node_addon.config.short_name), **kwargs), 'exp': timezone.now() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), self.JWE_KEY)} return api_url_for('get_auth', **options)
def test_no_key_wrapping(self): data = jwe.encrypt(b"Just Some Data", jwe.kdf(b"key", b"Salt")).split(b".") data[1] = b"cmFwcGE=" with pytest.raises(jwe.exceptions.UnsupportedOption) as e: jwe.decrypt(b".".join(data), jwe.kdf(b"key", b"Salt")) assert e.value.args[0] == "Key wrapping is currently not supported"
def test_improper_key(self): key = jwe.kdf(b'Testing', b'Pepper') data = b'Just some data' encrypted = jwe.encrypt(data, key) with pytest.raises(InvalidTag): # TODO make this a custom exception jwe.decrypt(encrypted, jwe.kdf(b'somekey', b'Salt')) == data
def test_invalid_header_json(self): with pytest.raises(jwe.exceptions.MalformedData) as e: jwe.decrypt( jwe.encrypt(b"Just Some Data", jwe.kdf(b"key", b"Salt"))[3:], # Cut out some of the JSON jwe.kdf(b"key", b"Salt"), ) assert e.value.args[0] == "Header is not valid JSON"
def test_improper_key(self): key = jwe.kdf(b"Testing", b"Pepper") data = b"Just some data" encrypted = jwe.encrypt(data, key) with pytest.raises(InvalidTag): # TODO make this a custom exception jwe.decrypt(encrypted, jwe.kdf(b"somekey", b"Salt")) == data
def test_no_key_wrapping(self): data = jwe.encrypt(b'Just Some Data', jwe.kdf(b'key', b'Salt')).split(b'.') data[1] = b'cmFwcGE=' with pytest.raises(jwe.exceptions.UnsupportedOption) as e: jwe.decrypt(b'.'.join(data), jwe.kdf(b'key', b'Salt')) assert e.value.args[0] == 'Key wrapping is currently not supported'
def test_invalid_header_json(self): with pytest.raises(jwe.exceptions.MalformedData) as e: jwe.decrypt( jwe.encrypt(b'Just Some Data', jwe.kdf(b'key', b'Salt'))[3:], # Cut out some of the JSON jwe.kdf(b'key', b'Salt')) assert e.value.args[0] == 'Header is not valid JSON'
def build_url(self, **kwargs): options = {'payload': jwe.encrypt(jwt.encode({'data': dict(dict( action='download', nid=self.preprint._id, metrics={'uri': settings.MFR_SERVER_URL}, provider='osfstorage'), **kwargs), 'exp': timezone.now() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), self.JWE_KEY)} return api_url_for('get_auth', **options)
def get_db_prep_value(self, value, **kwargs): if value and not value.startswith(self.prefix): value = ensure_bytes(value) if not settings.RUNNING_MIGRATION: # don't encrypt things if we're migrating. value = self.prefix + jwe.encrypt(bytes(value), SENSITIVE_DATA_KEY) else: # just prefix them return u'jwe:::{}'.format(value) return value
def encrypt_string(value, prefix='jwe:::'): if value and not value.startswith(prefix): value = ensure_bytes(value) try: value = prefix + jwe.encrypt(bytes(value), SENSITIVE_DATA_KEY) except InvalidTag: # Allow use of an encrypted DB locally without encrypting fields if settings.DEBUG_MODE: pass else: raise return value
def get_db_prep_value(self, value, **kwargs): if value and not value.startswith(self.prefix): value = ensure_bytes(value) try: value = self.prefix + jwe.encrypt(bytes(value), SENSITIVE_DATA_KEY) except InvalidTag: # Allow use of an encrypted DB locally without encrypting fields if settings.DEBUG_MODE: pass else: raise return value
def build_payload(self, bundle, view_only=None, cookie=None): query_params = {} if cookie: bundle['cookie'] = cookie if view_only: # View only must go outside of the jwt query_params['view_only'] = view_only query_params['payload'] = jwe.encrypt(jwt.encode({ 'data': bundle, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION) }, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM), JWE_KEY) return query_params
def build_payload(self, username): data = { 'provider': { 'id': self.institution._id, 'user': { 'middleNames': '', 'familyName': '', 'givenName': '', 'fullname': 'Fake User', 'suffix': '', 'username': username } } } return jwe.encrypt(jwt.encode({ 'sub': username, 'data': json.dumps(data) }, settings.JWT_SECRET, algorithm='HS256'), settings.JWE_SECRET)
def build_url(self, **kwargs): options = { "payload": jwe.encrypt( jwt.encode( { "data": dict( dict(action="download", nid=self.node._id, provider=self.node_addon.config.short_name), **kwargs ), "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM, ), self.JWE_KEY, ) } return api_url_for("get_auth", **options)
def make_payload( institution, username, fullname='Fake User', given_name='', family_name='' ): data = { 'provider': { 'id': institution._id, 'user': { 'middleNames': '', 'familyName': family_name, 'givenName': given_name, 'fullname': fullname, 'suffix': '', 'username': username } } } return jwe.encrypt(jwt.encode({ 'sub': username, 'data': json.dumps(data) }, settings.JWT_SECRET, algorithm='HS256'), settings.JWE_SECRET)
def make_payload( institution, username, fullname='Fake User', given_name='', family_name='', department='', is_member_of='', selective_sso_filter='', ): data = { 'provider': { 'id': institution._id, 'user': { 'middleNames': '', 'familyName': family_name, 'givenName': given_name, 'fullname': fullname, 'suffix': '', 'username': username, 'department': department, 'isMemberOf': is_member_of, 'selectiveSsoFilter': selective_sso_filter, } } } return jwe.encrypt( jwt.encode( { 'sub': username, 'data': json.dumps(data) }, settings.JWT_SECRET, algorithm='HS256' ), settings.JWE_SECRET )
def build_payload(self, bundle, view_only=None, cookie=None): query_params = {} if cookie: bundle['cookie'] = cookie if view_only: # View only must go outside of the jwt query_params['view_only'] = view_only query_params['payload'] = jwe.encrypt( jwt.encode( { 'data': bundle, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION) }, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM), JWE_KEY) return query_params
def get_auth(auth, **kwargs): cas_resp = None if not auth.user: # Central Authentication Server OAuth Bearer Token authorization = request.headers.get('Authorization') if authorization and authorization.startswith('Bearer '): client = cas.get_client() try: access_token = cas.parse_auth_header(authorization) cas_resp = client.profile(access_token) except cas.CasError as err: sentry.log_exception() # NOTE: We assume that the request is an AJAX request return json_renderer(err) if cas_resp.authenticated: auth.user = OSFUser.load(cas_resp.user) try: data = jwt.decode(jwe.decrypt( request.args.get('payload', '').encode('utf-8'), WATERBUTLER_JWE_KEY), settings.WATERBUTLER_JWT_SECRET, options={'require_exp': True}, algorithm=settings.WATERBUTLER_JWT_ALGORITHM)['data'] except (jwt.InvalidTokenError, KeyError) as err: sentry.log_message(str(err)) raise HTTPError(http_status.HTTP_403_FORBIDDEN) if not auth.user: auth.user = OSFUser.from_cookie(data.get('cookie', '')) try: action = data['action'] node_id = data['nid'] provider_name = data['provider'] except KeyError: raise HTTPError(http_status.HTTP_400_BAD_REQUEST) node = AbstractNode.load(node_id) or Preprint.load(node_id) if node and node.is_deleted: raise HTTPError(http_status.HTTP_410_GONE) elif not node: raise HTTPError(http_status.HTTP_404_NOT_FOUND) check_access(node, auth, action, cas_resp) provider_settings = None if hasattr(node, 'get_addon'): provider_settings = node.get_addon(provider_name) if not provider_settings: raise HTTPError(http_status.HTTP_400_BAD_REQUEST) path = data.get('path') credentials = None waterbutler_settings = None fileversion = None if provider_name == 'osfstorage': if path: file_id = path.strip('/') # check to see if this is a file or a folder filenode = OsfStorageFileNode.load(path.strip('/')) if filenode and filenode.is_file: # default to most recent version if none is provided in the response version = int(data['version']) if data.get( 'version') else filenode.versions.count() try: fileversion = FileVersion.objects.filter( basefilenode___id=file_id, identifier=version).select_related('region').get() except FileVersion.DoesNotExist: raise HTTPError(http_status.HTTP_400_BAD_REQUEST) if auth.user: # mark fileversion as seen FileVersionUserMetadata.objects.get_or_create( user=auth.user, file_version=fileversion) if not node.is_contributor_or_group_member(auth.user): from_mfr = download_is_from_mfr(request, payload=data) # version index is 0 based version_index = version - 1 if action == 'render': update_analytics(node, filenode, version_index, 'view') elif action == 'download' and not from_mfr: update_analytics(node, filenode, version_index, 'download') if waffle.switch_is_active(features.ELASTICSEARCH_METRICS): if isinstance(node, Preprint): metric_class = get_metric_class_for_action( action, from_mfr=from_mfr) if metric_class: sloan_flags = { 'sloan_id': request.cookies.get(SLOAN_ID_COOKIE_NAME) } for flag_name in SLOAN_FLAGS: value = request.cookies.get( f'dwf_{flag_name}_custom_domain' ) or request.cookies.get( f'dwf_{flag_name}') if value: sloan_flags[flag_name.replace( '_display', '')] = strtobool(value) try: metric_class.record_for_preprint( preprint=node, user=auth.user, version=fileversion.identifier if fileversion else None, path=path, **sloan_flags) except es_exceptions.ConnectionError: log_exception() if fileversion and provider_settings: region = fileversion.region credentials = region.waterbutler_credentials waterbutler_settings = fileversion.serialize_waterbutler_settings( node_id=provider_settings.owner._id, root_id=provider_settings.root_node._id, ) # If they haven't been set by version region, use the NodeSettings or Preprint directly if not (credentials and waterbutler_settings): credentials = node.serialize_waterbutler_credentials(provider_name) waterbutler_settings = node.serialize_waterbutler_settings( provider_name) if isinstance(credentials.get('token'), bytes): credentials['token'] = credentials.get('token').decode() return { 'payload': jwe.encrypt( jwt.encode( { 'exp': timezone.now() + datetime.timedelta( seconds=settings.WATERBUTLER_JWT_EXPIRATION), 'data': { 'auth': make_auth( auth.user ), # A waterbutler auth dict not an Auth object 'credentials': credentials, 'settings': waterbutler_settings, 'callback_url': node.api_url_for( ('create_waterbutler_log' if not getattr(node, 'is_registration', False) else 'registration_callbacks'), _absolute=True, _internal=True) } }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), WATERBUTLER_JWE_KEY).decode() }
def get_auth(auth, **kwargs): cas_resp = None if not auth.user: # Central Authentication Server OAuth Bearer Token authorization = request.headers.get("Authorization") if authorization and authorization.startswith("Bearer "): client = cas.get_client() try: access_token = cas.parse_auth_header(authorization) cas_resp = client.profile(access_token) except cas.CasError as err: sentry.log_exception() # NOTE: We assume that the request is an AJAX request return json_renderer(err) if cas_resp.authenticated: auth.user = User.load(cas_resp.user) try: data = jwt.decode( jwe.decrypt(request.args.get("payload", "").encode("utf-8"), WATERBUTLER_JWE_KEY), settings.WATERBUTLER_JWT_SECRET, options={"require_exp": True}, algorithm=settings.WATERBUTLER_JWT_ALGORITHM, )["data"] except (jwt.InvalidTokenError, KeyError): raise HTTPError(httplib.FORBIDDEN) if not auth.user: auth.user = User.from_cookie(data.get("cookie", "")) try: action = data["action"] node_id = data["nid"] provider_name = data["provider"] except KeyError: raise HTTPError(httplib.BAD_REQUEST) node = Node.load(node_id) if not node: raise HTTPError(httplib.NOT_FOUND) check_access(node, auth, action, cas_resp) provider_settings = node.get_addon(provider_name) if not provider_settings: raise HTTPError(httplib.BAD_REQUEST) try: credentials = provider_settings.serialize_waterbutler_credentials() waterbutler_settings = provider_settings.serialize_waterbutler_settings() except exceptions.AddonError: log_exception() raise HTTPError(httplib.BAD_REQUEST) return { "payload": jwe.encrypt( jwt.encode( { "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), "data": { "auth": make_auth(auth.user), # A waterbutler auth dict not an Auth object "credentials": credentials, "settings": waterbutler_settings, "callback_url": node.api_url_for( ("create_waterbutler_log" if not node.is_registration else "registration_callbacks"), _absolute=True, ), }, }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM, ), WATERBUTLER_JWE_KEY, ) }
def encrypt(value): if value: return jwe.encrypt(value.encode('utf-8'), SENSITIVE_DATA_KEY) return None
def get_auth(auth, **kwargs): cas_resp = None if not auth.user: # Central Authentication Server OAuth Bearer Token authorization = request.headers.get('Authorization') if authorization and authorization.startswith('Bearer '): client = cas.get_client() try: access_token = cas.parse_auth_header(authorization) cas_resp = client.profile(access_token) except cas.CasError as err: sentry.log_exception() # NOTE: We assume that the request is an AJAX request return json_renderer(err) if cas_resp.authenticated: auth.user = User.load(cas_resp.user) try: data = jwt.decode( jwe.decrypt(request.args.get('payload', '').encode('utf-8'), WATERBUTLER_JWE_KEY), settings.WATERBUTLER_JWT_SECRET, options={'require_exp': True}, algorithm=settings.WATERBUTLER_JWT_ALGORITHM )['data'] except (jwt.InvalidTokenError, KeyError): raise HTTPError(httplib.FORBIDDEN) if not auth.user: auth.user = User.from_cookie(data.get('cookie', '')) try: action = data['action'] node_id = data['nid'] provider_name = data['provider'] except KeyError: raise HTTPError(httplib.BAD_REQUEST) node = Node.load(node_id) if not node: raise HTTPError(httplib.NOT_FOUND) check_access(node, auth, action, cas_resp) provider_settings = node.get_addon(provider_name) if not provider_settings: raise HTTPError(httplib.BAD_REQUEST) try: credentials = provider_settings.serialize_waterbutler_credentials() waterbutler_settings = provider_settings.serialize_waterbutler_settings() except exceptions.AddonError: log_exception() raise HTTPError(httplib.BAD_REQUEST) return {'payload': jwe.encrypt(jwt.encode({ 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), 'data': { 'auth': make_auth(auth.user), # A waterbutler auth dict not an Auth object 'credentials': credentials, 'settings': waterbutler_settings, 'callback_url': node.api_url_for( ('create_waterbutler_log' if not node.is_registration else 'registration_callbacks'), _absolute=True, ), } }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), WATERBUTLER_JWE_KEY)}
def encrypt_key(document, key): database['externalaccount'].find_and_modify( {'_id': document['_id']}, {'$set': { key: jwe.encrypt(bytes(jwe.decrypt(document[key].encode('utf-8'), SENSITIVE_DATA_KEY)), SENSITIVE_DATA_KEY) }})
def encrypt(value): if value: return jwe.encrypt(bytes(value), SENSITIVE_DATA_KEY) return None
def get_auth(auth, **kwargs): cas_resp = None if not auth.user: # Central Authentication Server OAuth Bearer Token authorization = request.headers.get('Authorization') if authorization and authorization.startswith('Bearer '): client = cas.get_client() try: access_token = cas.parse_auth_header(authorization) cas_resp = client.profile(access_token) except cas.CasError as err: sentry.log_exception() # NOTE: We assume that the request is an AJAX request return json_renderer(err) if cas_resp.authenticated: auth.user = OSFUser.load(cas_resp.user) try: data = jwt.decode( jwe.decrypt(request.args.get('payload', '').encode('utf-8'), WATERBUTLER_JWE_KEY), settings.WATERBUTLER_JWT_SECRET, options={'require_exp': True}, algorithm=settings.WATERBUTLER_JWT_ALGORITHM )['data'] except (jwt.InvalidTokenError, KeyError) as err: sentry.log_message(str(err)) raise HTTPError(httplib.FORBIDDEN) if not auth.user: auth.user = OSFUser.from_cookie(data.get('cookie', '')) try: action = data['action'] node_id = data['nid'] provider_name = data['provider'] except KeyError: raise HTTPError(httplib.BAD_REQUEST) node = AbstractNode.load(node_id) or Preprint.load(node_id) if not node: raise HTTPError(httplib.NOT_FOUND) check_access(node, auth, action, cas_resp) provider_settings = None if hasattr(node, 'get_addon'): provider_settings = node.get_addon(provider_name) if not provider_settings: raise HTTPError(httplib.BAD_REQUEST) try: path = data.get('path') version = data.get('version') credentials = None waterbutler_settings = None fileversion = None if provider_name == 'osfstorage': if path and version: # check to see if this is a file or a folder filenode = OsfStorageFileNode.load(path.strip('/')) if filenode and filenode.is_file: try: fileversion = FileVersion.objects.filter( basefilenode___id=path.strip('/'), identifier=version ).select_related('region').get() except FileVersion.DoesNotExist: raise HTTPError(httplib.BAD_REQUEST) # path and no version, use most recent version elif path: filenode = OsfStorageFileNode.load(path.strip('/')) if filenode and filenode.is_file: fileversion = FileVersion.objects.filter( basefilenode=filenode ).select_related('region').order_by('-created').first() if fileversion: region = fileversion.region credentials = region.waterbutler_credentials waterbutler_settings = fileversion.serialize_waterbutler_settings( node_id=provider_settings.owner._id if provider_settings else node._id, root_id=provider_settings.root_node._id if provider_settings else node.root_folder._id, ) # If they haven't been set by version region, use the NodeSettings region if not (credentials and waterbutler_settings): credentials = node.serialize_waterbutler_credentials(provider_name) waterbutler_settings = node.serialize_waterbutler_settings(provider_name) except exceptions.AddonError: log_exception() raise HTTPError(httplib.BAD_REQUEST) # TODO: Add a signal here? if waffle.switch_is_active(features.ELASTICSEARCH_METRICS): user = auth.user if isinstance(node, Preprint) and not node.is_contributor(user): metric_class = get_metric_class_for_action(action) if metric_class: try: metric_class.record_for_preprint( preprint=node, user=user, version=fileversion.identifier if fileversion else None, path=path ) except es_exceptions.ConnectionError: log_exception() return {'payload': jwe.encrypt(jwt.encode({ 'exp': timezone.now() + datetime.timedelta(seconds=settings.WATERBUTLER_JWT_EXPIRATION), 'data': { 'auth': make_auth(auth.user), # A waterbutler auth dict not an Auth object 'credentials': credentials, 'settings': waterbutler_settings, 'callback_url': node.api_url_for( ('create_waterbutler_log' if not getattr(node, 'is_registration', False) else 'registration_callbacks'), _absolute=True, _internal=True ) } }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), WATERBUTLER_JWE_KEY)}
def encrypt(value): if value: value = ensure_bytes(value) return jwe.encrypt(bytes(value), SENSITIVE_DATA_KEY) return None
def get_auth(auth, **kwargs): cas_resp = None if not auth.user: # Central Authentication Server OAuth Bearer Token authorization = request.headers.get('Authorization') if authorization and authorization.startswith('Bearer '): client = cas.get_client() try: access_token = cas.parse_auth_header(authorization) cas_resp = client.profile(access_token) except cas.CasError as err: sentry.log_exception() # NOTE: We assume that the request is an AJAX request return json_renderer(err) if cas_resp.authenticated: auth.user = OSFUser.load(cas_resp.user) try: data = jwt.decode(jwe.decrypt( request.args.get('payload', '').encode('utf-8'), WATERBUTLER_JWE_KEY), settings.WATERBUTLER_JWT_SECRET, options={'require_exp': True}, algorithm=settings.WATERBUTLER_JWT_ALGORITHM)['data'] except (jwt.InvalidTokenError, KeyError) as err: sentry.log_message(str(err)) raise HTTPError(httplib.FORBIDDEN) if not auth.user: auth.user = OSFUser.from_cookie(data.get('cookie', '')) try: action = data['action'] node_id = data['nid'] provider_name = data['provider'] except KeyError: raise HTTPError(httplib.BAD_REQUEST) node = AbstractNode.load(node_id) if not node: raise HTTPError(httplib.NOT_FOUND) check_access(node, auth, action, cas_resp) provider_settings = node.get_addon(provider_name) if not provider_settings: raise HTTPError(httplib.BAD_REQUEST) try: credentials = provider_settings.serialize_waterbutler_credentials() waterbutler_settings = provider_settings.serialize_waterbutler_settings( ) except exceptions.AddonError: log_exception() raise HTTPError(httplib.BAD_REQUEST) return { 'payload': jwe.encrypt( jwt.encode( { 'exp': timezone.now() + datetime.timedelta( seconds=settings.WATERBUTLER_JWT_EXPIRATION), 'data': { 'auth': make_auth( auth.user ), # A waterbutler auth dict not an Auth object 'credentials': credentials, 'settings': waterbutler_settings, 'callback_url': node.api_url_for(('create_waterbutler_log' if not node.is_registration else 'registration_callbacks'), _absolute=True, _internal=True), } }, settings.WATERBUTLER_JWT_SECRET, algorithm=settings.WATERBUTLER_JWT_ALGORITHM), WATERBUTLER_JWE_KEY) }
def login_ad(): # if request.method == "POST": tokendata = {"status": "fail"} data = {"status": "fail"} try: c = Connection(Server(config.ad_ip, port=389, use_ssl=False), auto_bind=AUTO_BIND_NO_TLS, read_only=True, check_names=True, user='******', password='******') if c.bind(): if "description" in c.result \ and c.result['description'] == "success" \ and "user" in request.json: c.search(search_base='DC=firsthealthinc,DC=com', search_filter='(&(samAccountName={}))'.format(request.json["user"]), search_scope=SUBTREE, attributes=["displayName", "distinguishedName", "memberOf", "sn", "givenName", "nTSecurityDescriptor", "msRASSavedFramedIPAddress", "networkAddress", 'title', 'physicalDeliveryOfficeName', 'thumbnailPhoto', "sAMAccountName", "mail", "mobile", "telephoneNumber", "department", "company"], paged_size=5) # c.search(search_base='DC=firsthealthinc,DC=com', search_filter='(&(CN=*))') # # result = c.response_to_json() if len(json.loads(c.response_to_json())['entries']) > 0 and "password" in request.json: tempV = json.loads(c.response_to_json()) c.rebind(user="******".format(request.json["user"]), password=request.json["password"]) if c.result['description'] == "success": data['usercredits'] = c.result user = tempV["entries"][0] data["displayName"] = user["attributes"]["displayName"] data["accountName"] = user["attributes"]["sAMAccountName"] data["mail"] = user["attributes"]["mail"] data['firstname'] = user["attributes"]['givenName'] data['lastname'] = user["attributes"]['sn'] data["level"] = (user["attributes"]["distinguishedName"]).split(",")[1].split("=")[1] data["memberOf"] = [x.split(",")[0].split("=")[1] for x in (user["attributes"]["memberOf"])] data['company'] = user['attributes']['company'] or "" if user['attributes']['thumbnailPhoto']: data['thumbnailPhoto'] = user['attributes']['thumbnailPhoto']['encoded'] else: data['thumbnailPhoto'] = None if user['attributes']['title']: data['title'] = user['attributes']['title'] else: data['title'] = None if user['attributes']['physicalDeliveryOfficeName']: data['physicalDeliveryOfficeName'] = user['attributes']['physicalDeliveryOfficeName'] else: data['physicalDeliveryOfficeName'] = None if user['attributes']['telephoneNumber']: data['phone'] = user['attributes']['telephoneNumber'] else: data['phone'] = None """ DATABASE RULES THESE ARE DO TO CHANGE """ u = d.Users.query.filter_by(accountname=data["accountName"]).first() if not u: if data['level'] == "Admins": userlevel = 5 else: userlevel = 1 if "Domain Admins" in data['memberOf']: userlevel = 9 u = d.Users( email=data['mail'], accountname=data['accountName'], userlevel=userlevel, displayname=data['displayName'], ) u.firstname = data['firstname'] u.lastname = data['lastname'] u.organization = data['company'] u.phone=data['phone'] u.title = data['title'] u.thumbnailphoto = data['thumbnailPhoto'] u.physicaldeliveryofficename = data['physicalDeliveryOfficeName'] d.db.session.add(u) d.db.session.commit() theAll = d.Department.query.filter_by(department="ALL").first() if theAll and theAll not in u.departments: u.departments.append(theAll) for i in data["memberOf"]: dep = d.Department.query.filter_by(department=i).first() if i not in [x.department for x in u.departments] and dep: u.departments.append(dep) d.db.session.commit() else: u = d.Users.query.filter_by(accountname=data['accountName']).first_or_404() if data['level'] == "Admins": u.userlevel = 5 else: u.userlevel = 1 if "Domain Admins" in data['memberOf']: u.userlevel = 9 u.email = data['mail'] u.accountname = data['accountName'] u.displayname = data['displayName'] u.firstname = data['firstname'] u.lastname = data['lastname'] u.organization=data['company'] u.phone=data['phone'] u.title = data['title'] u.thumbnailphoto = data['thumbnailPhoto'] u.physicaldeliveryofficename = data['physicalDeliveryOfficeName'] #dept = d.Department.query.filter(d.Department.department != "ALL").all() d.db.session.commit() count = 0 if u.departments: for i in u.departments: count = count + 1 u.departments.remove(i) d.db.session.commit() u.departments.append(d.Department.query.filter_by(department="ALL").first_or_404()) for i in data["memberOf"]: dep = d.Department.query.filter_by(department=i).first() if i not in [x.department for x in u.departments] and dep: u.departments.append(dep) if u.userlevel == 9: if "MRI Techs" not in [x.department for x in u.departments]: mri = database.Department.query.filter_by(department="MRI Techs").first() if mri: u.departments.append(mri) d.db.session.commit() """ END """ """ GET USER REST """ u = d.Users.query.get(u.id) ud = [x.id for x in u.departments] data['user'] = d.asdict(u) data['departments'] = [d.asdict(x) for x in d.Department.query.all() if x.id in ud] # if u.userlevel != 9: # data['messages'] = [x.getDict() for x in d.Message.query.order_by(d.Message.id.desc()).all() # if x.department in ud] # data['departments'] = [d.asdict(x) for x in d.Department.query.all() if x.id in ud] # else: # data['messages'] = [x.getDict() for x in # d.Message.query.order_by(d.Message.id.desc()).all()] # data['departments'] = [d.asdict(x) for x in d.Department.query.all()] # for i in data['messages']: # i['user_confirm'] = len( # d.MessageConfirmed.query.filter_by(user=u.id, message=i['id']).all()) data['status'] = "success" tokendata = {} token = { 'expires': str(datetime.datetime.now() + timedelta(hours=10)), 'userlevel': u.userlevel, 'id': u.id, 'displayname': u.displayname, 'accountname': u.accountname } tokendata['token'] = jwe.encrypt(str.encode(json.dumps(token)), JWE.getEncode()).decode('UTF-8') tokendata['status'] = "success" tokendata['name'] = u.displayname tokendata['userlevel'] = u.userlevel else: data['message'] = "wrong user creds" tokendata['message'] = "wrong user creds" else: data["message"] = "wrong password" tokendata['message'] = "wrong password" else: data['message'] = "wrong user creds" tokendata['message'] = "wrong user creds" else: data["message"] = "can't reach active directory" tokendata['message'] = "can't reach active directory" except Exception as e: data['message'] = str(e) tokendata['message'] = str(e) finally: c.unbind() del c return json.dumps(tokendata, indent=4, sort_keys=True)