Skip to content

Commit bba34eb

Browse files
committed
rework page attributes
1 parent 86612bd commit bba34eb

File tree

1 file changed

+89
-98
lines changed

1 file changed

+89
-98
lines changed

encryptcontent/plugin.py

Lines changed: 89 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ def __encrypt_text_aes__(self, text, password):
112112
PADDING_CHAR
113113
)
114114

115-
def __encrypt_content__(self, content, password, base_path, encryptcontent_path, summary, encryption_info_message, obfuscate):
115+
def __encrypt_content__(self, content, base_path, encryptcontent_path, encryptcontent):
116116
""" Replaces page or article content with decrypt form. """
117-
ciphertext_bundle = self.__encrypt_text_aes__(content, password)
117+
ciphertext_bundle = self.__encrypt_text_aes__(content, encryptcontent['password'])
118118

119119
# optionally selfhost cryptojs
120120
if self.config["selfhost"]:
@@ -124,19 +124,20 @@ def __encrypt_content__(self, content, password, base_path, encryptcontent_path,
124124
else:
125125
js_libraries = JS_LIBRARIES
126126

127+
obfuscate = encryptcontent.get('obfuscate')
127128
if obfuscate:
128-
obfuscate_password = password
129+
obfuscate_password = encryptcontent['password']
129130
else:
130131
obfuscate_password = None
131132

132133
decrypt_form = Template(self.setup['html_template']).render({
133134
# custom message and template rendering
134-
'summary': summary,
135-
'placeholder': self.setup['placeholder'],
135+
'summary': encryptcontent['summary'],
136+
'placeholder': encryptcontent['placeholder'],
136137
'password_button': self.config['password_button'],
137-
'password_button_text': self.setup['password_button_text'],
138-
'encryption_info_message': encryption_info_message,
139-
'decryption_failure_message': json.dumps(self.setup['decryption_failure_message']),
138+
'password_button_text': encryptcontent['password_button_text'],
139+
'encryption_info_message': encryptcontent['encryption_info_message'],
140+
'decryption_failure_message': json.dumps(encryptcontent['decryption_failure_message']),
140141
'input_class': self.config['input_class'],
141142
'button_class': self.config['button_class'],
142143
'obfuscate': obfuscate,
@@ -295,14 +296,6 @@ def on_config(self, config, **kwargs):
295296
if not self.setup['search_plugin_found']:
296297
logger.warning('"search" plugin wasn\'t enabled. Search index isn\'t generated or modified.')
297298

298-
#init default translation from config
299-
self.setup['title_prefix'] = self.config['title_prefix']
300-
self.setup['summary'] = self.config['summary']
301-
self.setup['placeholder'] = self.config['placeholder']
302-
self.setup['password_button_text'] = self.config['password_button_text']
303-
self.setup['decryption_failure_message'] = self.config['decryption_failure_message']
304-
self.setup['encryption_info_message'] = self.config['encryption_info_message']
305-
306299
self.setup['locations'] = {}
307300

308301
def on_pre_build(self, config, **kwargs):
@@ -349,27 +342,23 @@ def on_page_markdown(self, markdown, page, config, **kwargs):
349342
:return: Markdown source text of page as string
350343
"""
351344

352-
# Set global password as default password for each page
353-
self.setup['password'] = self.config['global_password']
345+
encryptcontent = {} #init page data dict
354346

355-
# Custom per-page strings
356-
if 'summary' in page.meta.keys():
357-
setattr(page, 'custom_summary', str(page.meta.get('summary')))
358-
if 'encryption_info_message' in page.meta.keys():
359-
setattr(page, 'custom_encryption_info_message', str(page.meta.get('encryption_info_message')))
347+
# Set global password as default password for each page
348+
encryptcontent['password'] = self.config['global_password']
360349

361350
if 'password' in page.meta.keys():
362351
# If global_password is set, but you don't want to encrypt content
363352
page_password = str(page.meta.get('password'))
364-
self.setup['password'] = None if page_password == '' else page_password
353+
encryptcontent['password'] = None if page_password == '' else page_password
365354
# Delete meta password information before rendering to avoid leak :]
366355
del page.meta['password']
367356

368357
if 'use_secret' in page.meta.keys():
369358
if os.environ.get(str(page.meta.get('use_secret'))):
370-
self.setup['password'] = os.environ.get(str(page.meta.get('use_secret')))
359+
encryptcontent['password'] = os.environ.get(str(page.meta.get('use_secret')))
371360
else:
372-
if self.config['ignore_missing_secret'] and self.setup['password']:
361+
if self.config['ignore_missing_secret'] and encryptcontent['password']:
373362
logger.warning('Cannot get password for "{page}" from environment variable: {var}. Using password from config or meta key as fallback!'.format(
374363
var=str(page.meta.get('use_secret')), page=page.title)
375364
)
@@ -380,11 +369,23 @@ def on_page_markdown(self, markdown, page, config, **kwargs):
380369
os._exit(1) # prevent build without password to avoid leak0
381370

382371
if 'obfuscate' in page.meta.keys():
383-
if self.setup['password'] is None: # Only allow obfuscation if no password defined
384-
setattr(page, 'obfuscate', True)
385-
self.setup['password'] = str(page.meta.get('obfuscate'))
372+
if encryptcontent['password'] is None: # Only allow obfuscation if no password defined
373+
encryptcontent['obfuscate'] = True
374+
encryptcontent['password'] = str(page.meta.get('obfuscate'))
386375
del page.meta['obfuscate']
387376

377+
if encryptcontent.get('password'):
378+
# Custom per-page strings
379+
if 'encryption_summary' in page.meta.keys():
380+
encryptcontent['summary'] = str(page.meta.get('encryption_summary'))
381+
del page.meta['encryption_summary']
382+
383+
if 'encryption_info_message' in page.meta.keys():
384+
encryptcontent['encryption_info_message'] = str(page.meta.get('encryption_info_message'))
385+
del page.meta['encryption_info_message']
386+
387+
setattr(page, 'encryptcontent', encryptcontent)
388+
388389
return markdown
389390

390391
def on_page_content(self, html, page, config, **kwargs):
@@ -400,19 +401,15 @@ def on_page_content(self, html, page, config, **kwargs):
400401
:param site_navigation: global navigation object
401402
:return: HTML rendered from Markdown source as string encrypt with AES
402403
"""
403-
if self.setup['password'] is not None:
404+
405+
if hasattr(page, 'encryptcontent'):
404406
if self.config['tag_encrypted_page']:
405407
# Set attribute on page to identify encrypted page on template rendering
406408
setattr(page, 'encrypted', True)
407409

408-
# Set password attributes on page for other mkdocs events
409-
setattr(page, 'password', str(self.setup['password']))
410-
411410
# Keep encrypted html to encrypt as temporary variable on page
412411
if not self.config['inject']:
413-
setattr(page, 'html_to_encrypt', html)
414-
415-
self.setup['password'] = None #reinit for next page
412+
page.encryptcontent['html_to_encrypt'] = html
416413

417414
return html
418415

@@ -429,69 +426,59 @@ def on_page_context(self, context, page, config, **kwargs):
429426
:param nav: global navigation object
430427
:return: dict of template context variables
431428
"""
432-
if hasattr(page, 'password'):
429+
if hasattr(page, 'encryptcontent'):
433430
if 'i18n_page_file_locale' in context:
434431
locale = context['i18n_page_file_locale']
435432
if locale in self.config['translations']:
436-
#init default translation from config
437-
self.setup['title_prefix'] = self.config['title_prefix']
438-
self.setup['summary'] = self.config['summary']
439-
self.setup['placeholder'] = self.config['placeholder']
440-
self.setup['password_button_text'] = self.config['password_button_text']
441-
self.setup['decryption_failure_message'] = self.config['decryption_failure_message']
442-
self.setup['encryption_info_message'] = self.config['encryption_info_message']
443433
translations = self.config['translations'][locale]
434+
444435
#apply translation if defined
445-
if 'title_prefix' in translations:
446-
self.setup['title_prefix'] = translations['title_prefix']
447-
if 'summary' in translations:
448-
self.setup['summary'] = translations['summary']
449-
if 'placeholder' in translations:
450-
self.setup['placeholder'] = translations['placeholder']
451-
if 'password_button_text' in translations:
452-
self.setup['password_button_text'] = translations['password_button_text']
453-
if 'decryption_failure_message' in translations:
454-
self.setup['decryption_failure_message'] = translations['decryption_failure_message']
455-
if 'encryption_info_message' in translations:
456-
self.setup['encryption_info_message'] = translations['encryption_info_message']
457-
458-
if self.setup['title_prefix']:
436+
if 'title_prefix' in translations and 'title_prefix' not in page.encryptcontent:
437+
page.encryptcontent['title_prefix'] = translations['title_prefix']
438+
if 'summary' in translations and 'summary' not in page.encryptcontent:
439+
page.encryptcontent['summary'] = translations['summary']
440+
if 'placeholder' in translations and 'placeholder' not in page.encryptcontent:
441+
page.encryptcontent['placeholder'] = translations['placeholder']
442+
if 'password_button_text' in translations and 'password_button_text' not in page.encryptcontent:
443+
page.encryptcontent['password_button_text'] = translations['password_button_text']
444+
if 'decryption_failure_message' in translations and 'decryption_failure_message' not in page.encryptcontent:
445+
page.encryptcontent['decryption_failure_message'] = translations['decryption_failure_message']
446+
if 'encryption_info_message' in translations and 'encryption_info_message' not in page.encryptcontent:
447+
page.encryptcontent['encryption_info_message'] = translations['encryption_info_message']
448+
449+
#init default strings from config
450+
if 'title_prefix' not in page.encryptcontent:
451+
page.encryptcontent['title_prefix'] = self.config['title_prefix']
452+
if 'summary' not in page.encryptcontent:
453+
page.encryptcontent['summary'] = self.config['summary']
454+
if 'placeholder' not in page.encryptcontent:
455+
page.encryptcontent['placeholder'] = self.config['placeholder']
456+
if 'password_button_text' not in page.encryptcontent:
457+
page.encryptcontent['password_button_text'] = self.config['password_button_text']
458+
if 'decryption_failure_message' not in page.encryptcontent:
459+
page.encryptcontent['decryption_failure_message'] = self.config['decryption_failure_message']
460+
if 'encryption_info_message' not in page.encryptcontent:
461+
page.encryptcontent['encryption_info_message'] = self.config['encryption_info_message']
462+
463+
if page.encryptcontent['title_prefix']:
459464
page.title = str(self.config['title_prefix']) + str(page.title)
460465

461-
if hasattr(page, 'custom_summary'):
462-
summary = page.custom_summary
463-
else:
464-
summary = self.setup['summary']
465-
466-
if hasattr(page, 'custom_encryption_info_message'):
467-
encryption_info_message = page.custom_encryption_info_message
468-
else:
469-
encryption_info_message = self.setup['encryption_info_message']
470-
471-
obfuscate = hasattr(page, 'obfuscate')
472-
473-
if hasattr(page, 'html_to_encrypt'):
474-
page.content = self.__encrypt_content__(
475-
page.html_to_encrypt,
476-
str(page.password),
477-
context['base_url']+'/',
478-
self.setup['site_path']+page.url,
479-
summary,
480-
encryption_info_message,
481-
obfuscate
482-
)
483-
delattr(page, 'html_to_encrypt')
484-
485-
if self.config['inject']:
486-
setattr(page, 'decrypt_form', self.__encrypt_content__(
487-
'<!-- dummy -->',
488-
str(page.password),
489-
context['base_url']+'/',
490-
self.setup['site_path']+page.url,
491-
summary,
492-
encryption_info_message,
493-
obfuscate
494-
))
466+
if 'html_to_encrypt' in page.encryptcontent:
467+
page.content = self.__encrypt_content__(
468+
page.encryptcontent['html_to_encrypt'],
469+
context['base_url']+'/',
470+
self.setup['site_path']+page.url,
471+
page.encryptcontent
472+
)
473+
page.encryptcontent['html_to_encrypt'] = None
474+
475+
if self.config['inject']:
476+
page.encryptcontent['decrypt_form'] = self.__encrypt_content__(
477+
'<!-- dummy -->',
478+
context['base_url']+'/',
479+
self.setup['site_path']+page.url,
480+
page.encryptcontent
481+
)
495482

496483
return context
497484

@@ -508,7 +495,7 @@ def on_post_page(self, output_content, page, config, **kwargs):
508495
:return: output of rendered template as string
509496
"""
510497
# Limit this process only if encrypted_something feature is enable *(speedup)*
511-
if (self.setup['encrypted_something'] and hasattr(page, 'password')
498+
if (self.setup['encrypted_something'] and hasattr(page, 'encryptcontent')
512499
and len(self.setup['encrypted_something']) > 0): # noqa: W503
513500
soup = BeautifulSoup(output_content, 'html.parser')
514501
for name, tag in self.setup['encrypted_something'].items():
@@ -529,7 +516,7 @@ def on_post_page(self, output_content, page, config, **kwargs):
529516
else:
530517
merge_item = ""
531518
# Encrypt child items on target tags with page password
532-
cipher_bundle = self.__encrypt_text_aes__(merge_item, str(page.password))
519+
cipher_bundle = self.__encrypt_text_aes__(merge_item, str(page.encryptcontent['password']))
533520
encrypted_content = b';'.join(cipher_bundle).decode('ascii')
534521
# Replace initial content with encrypted one
535522
bs4_encrypted_content = BeautifulSoup(encrypted_content, 'html.parser')
@@ -542,19 +529,23 @@ def on_post_page(self, output_content, page, config, **kwargs):
542529
item['style'] = item['style'] + "display:none"
543530
else:
544531
item['style'] = "display:none"
532+
545533
if self.config['inject'] and len(self.config['inject']) == 1:
546534
name, tag = list(self.config['inject'].items())[0]
547535
injector = soup.new_tag("div")
548536
something_search = soup.find(tag[0], {tag[1]: name})
549537
something_search.insert_before(injector)
550-
injector.append(BeautifulSoup(page.decrypt_form, 'html.parser'))
551-
delattr(page, 'decrypt_form')
538+
injector.append(BeautifulSoup(page.encryptcontent['decrypt_form'], 'html.parser'))
539+
page.encryptcontent['decrypt_form'] = None
552540
output_content = str(soup)
553541

554-
if hasattr(page, 'password'):
542+
if hasattr(page, 'encryptcontent'):
555543
if self.setup['search_plugin_found']:
556544
location = page.url.lstrip('/')
557-
self.setup['locations'][location] = page.password
545+
self.setup['locations'][location] = page.encryptcontent['password']
546+
print(page.title)
547+
print(page.encryptcontent)
548+
delattr(page, 'encryptcontent')
558549

559550
return output_content
560551

0 commit comments

Comments
 (0)