"""Notifications logic.""" import hashlib import re import flask from oto import response from oto import status from oto.adaptors.flask import flaskify from owsrequest import request as requests from notifications.config import SYSTEM_ORCHARD_USER_ID from notifications.constants import error from notifications.constants.header import ORCHARD_USER_ID from notifications.constants.notifications import EMAIL_FEED_NAME from notifications.constants.notifications import NOTIFICATION_NAMES from notifications.constants.notifications import TOKEN_SECRET from notifications.constants.service_name import OWS_NOTIFICATIONS from notifications.logic import segment def unsubscribe(user_id, feed_name, feed_id, token): """Unsubscribe a user from a feed by calling ows-notifications. Args: user_id (str): the orchard user id. feed_name (str): the feed name. feed_id (str): the feed id. token (str): the sha1 hashed token. Returns: jinja2.Template: the unsubscribed template. """ generated_hash = hashlib.sha1() generated_hash.update(user_id.encode('utf-8')) generated_hash.update(feed_name.encode('utf-8')) generated_hash.update(feed_id.encode('utf-8')) generated_hash.update(TOKEN_SECRET.encode('utf-8')) generated_token = generated_hash.hexdigest() if generated_token != token: return flaskify(response.create_error_response( status=status.UNAUTHORIZED, code=error.ERROR_CODE_AUTHORIZATION, message=error.ERROR_MESSAGE_INVALID_TOKEN)) path = '/unsubscribe' headers = {} json = {} if re.match('(oa|alw):[0-9]+', user_id): headers[ORCHARD_USER_ID] = user_id json['user_feed_name'] = EMAIL_FEED_NAME json['feed_name'] = feed_name json['feed_id'] = feed_id else: headers[ORCHARD_USER_ID] = SYSTEM_ORCHARD_USER_ID json['user_feed_id'] = user_id json['user_feed_name'] = EMAIL_FEED_NAME json['feed_name'] = feed_name json['feed_id'] = feed_id result = requests.post( OWS_NOTIFICATIONS, path, headers=headers, json=json) if result.status_code != 200: return flaskify(response.create_error_response( status=result.status_code, code=error.ERROR_CODE_OWS_NOTIFICATIONS_REQUEST, message=result.json())) segment.track_unsubscribe(user_id, feed_name, feed_id) if re.match('^orchard_', feed_name): return flask.render_template( 'unsubscribed_orchard.html', notification_name=NOTIFICATION_NAMES[feed_name]) return flask.render_template( 'unsubscribed.html', notification_name=NOTIFICATION_NAMES[feed_name])