def clean_db(): """ Clean database for test. """ user = CRIPTsUser.objects(username=TUSER_NAME).first() if user: user.delete() user2 = CRIPTsUser.objects(username=TUSER2_NAME).first() if user2: user2.delete()
def prep_db(): """ Prep database for test. """ clean_db() # Add User user = CRIPTsUser.create_user(username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL) user.save() user2 = CRIPTsUser.create_user(username=TUSER2_NAME, password=TUSER2_PASS, email=TUSER2_EMAIL) user2.save()
def unsubscribe_user(username, stype, oid): """ Unsubscribe a user from this top-level object. :param username: The user to query for. :type username: str :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() for s in user.subscriptions[stype]: if str(s._id) == oid: user.subscriptions[stype].remove(s) break try: user.save() return {"success": True} except ValidationError, e: return {"success": False, "message": e}
def update_user_preference(username, section, values): """ Update a user preference. :param username: The user to query for. :type username: str :param section: The section in their preferences. :type section: str :param values: The values to set. :type values: str, list, dict :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: if not section in user.prefs: setattr(user.prefs, section, {}) # Something to think about.. do we want to do a replacement or a merge? setattr(user.prefs, section, values) try: user.save() return {'success': True} except ValidationError, e: return {'success': False, 'message': e}
def handle(self, *args, **options): """ Script Execution. """ # only look for active users who want email notifications users = CRIPTsUser.objects(is_active=True, prefs__notify__email=True) # only get the unprocessed notifications notifications = Notification.objects(status='new') for user in users: # only include notifications where the user is in the users list and # it wasn't created by them. includes = [x for x in notifications if user.username in x.users and user.username != x.analyst and x.obj_id != None] # only send an email if there's something to send if len(includes): email = EmailNotification(username=user.username, email=user.email) for include in includes: email.add_to_body(email.create_notification(include)) email.send_email() # clean up after ourselves usernames = [u.username for u in users] self.process_notifications(notifications, usernames)
def update_user_preference(username, section, values): """ Update a user preference. :param username: The user to query for. :type username: str :param section: The section in their preferences. :type section: str :param values: The values to set. :type values: str, list, dict :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: if not section in user.prefs: setattr(user.prefs, section, {}) # Something to think about.. do we want to do a replacement or a merge? setattr(user.prefs, section, values) try: user.save() return {"success": True} except ValidationError, e: return {"success": False, "message": e}
def subscribe_user(username, stype, oid): """ Subscribe a user to this top-level object. :param username: The user to query for. :type username: str :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser from cripts.core.user import EmbeddedSubscription username = str(username) es = EmbeddedSubscription() es._id = oid user = CRIPTsUser.objects(username=username).first() if stype in user.subscriptions: user.subscriptions[stype].append(es) else: user.subscriptions[stype] = [es] try: user.save() return {"success": True} except ValidationError, e: return {"success": False, "message": e}
def subscribe_user(username, stype, oid): """ Subscribe a user to this top-level object. :param username: The user to query for. :type username: str :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser from cripts.core.user import EmbeddedSubscription username = str(username) es = EmbeddedSubscription() es._id = oid user = CRIPTsUser.objects(username=username).first() if stype in user.subscriptions: user.subscriptions[stype].append(es) else: user.subscriptions[stype] = [es] try: user.save() return {'success': True} except ValidationError, e: return {'success': False, 'message': e}
def unsubscribe_user(username, stype, oid): """ Unsubscribe a user from this top-level object. :param username: The user to query for. :type username: str :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() for s in user.subscriptions[stype]: if str(s._id) == oid: user.subscriptions[stype].remove(s) break try: user.save() return {'success': True} except ValidationError, e: return {'success': False, 'message': e}
def get_subscribed_users(stype, oid, sources): """ Get users subscribed to this top-level object. :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: list :param sources: A list of sources of the top-level object. :type sources: list :returns: list """ from cripts.core.user import CRIPTsUser user_list = [] query = { '$or': [{ 'subscriptions.%s.id' % stype: ObjectId(oid) }, { 'subscriptions.Source.name': { '$in': sources } }] } users = CRIPTsUser.objects(__raw__=query) for user in users: user_list.append(user.username) return user_list
def create_general_notification(username, target_users, header, link_url, message, notification_type=NotificationType.ALERT): """ Generate a general notification -- not based on mongo obj. :param obj: The object. :type obj: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` :param username: The user creating the notification. :type username: str :param target_users: The list of users who will get the notification. :type target_users: list(str) :param header: The notification header message. :type header: list(str) :param link_url: A link URL for the header, specify None if there is no link. :type link_url: str :param message: The notification message. :type message: str :param notification_type: The notification type (e.g. alert, error). :type notification_type: str """ if notification_type not in NotificationType.ALL: notification_type = NotificationType.ALERT n = Notification() n.analyst = username n.notification_type = notification_type n.notification = message n.header = header n.link_url = link_url for target_user in target_users: # Check to make sure the user actually exists user = CRIPTsUser.objects(username=target_user).first() if user is not None: n.users.append(target_user) # don't notify the user creating this notification n.users = [u for u in n.users if u != username] if not len(n.users): return try: n.save() except ValidationError: pass # Signal potentially waiting threads that notification information is available for user in n.users: notification_lock = NotificationLockManager.get_notification_lock(user) notification_lock.acquire() try: notification_lock.notifyAll() finally: notification_lock.release()
def handle(self, *args, **options): """ Script Execution. """ # only look for active users who want email notifications users = CRIPTsUser.objects(is_active=True, prefs__notify__email=True) # only get the unprocessed notifications notifications = Notification.objects(status='new') for user in users: # only include notifications where the user is in the users list and # it wasn't created by them. includes = [ x for x in notifications if user.username in x.users and user.username != x.analyst and x.obj_id != None ] # only send an email if there's something to send if len(includes): email = EmailNotification(username=user.username, email=user.email) for include in includes: email.add_to_body(email.create_notification(include)) email.send_email() # clean up after ourselves usernames = [u.username for u in users] self.process_notifications(notifications, usernames)
def prep_db(): """ Prep database for test. """ clean_db() # Add User user = CRIPTsUser.create_user( username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL, ) user.save() user2 = CRIPTsUser.create_user( username=TUSER2_NAME, password=TUSER2_PASS, email=TUSER2_EMAIL, ) user2.save()
def toggle_user_preference(username, section, setting, is_enabled=False): """ Enables/Disables the target user preference :param username: The username that the preference toggle is for. :type username: str :param section: The section name where the preference is stored. :type section: str :param setting: The name of the setting within the section of the preference. :type setting: str :param is_enabled: An optional default value if the preference does not exist. :type is_enabled: str :returns: "success" (boolean), "message" (str) if failed, "state" (boolean) if successful """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: # Split the preference option into subtrees on '.' otree = setting.split(".") param = otree.pop() if not section in user.prefs: setattr(user.prefs, section, {}) opt = user.prefs[section] if len(otree): for subsect in otree: if not subsect in opt: opt[subsect] = {} opt = opt[subsect] else: opt = opt[subsect] if not param in opt: # if the preference doesn't exist, then try the fallback default value if is_enabled == True: opt[param] = False else: opt[param] = True else: # the preference exists, so use it if not opt[param]: opt[param] = True else: opt[param] = False try: user.save() return {"success": True, "state": opt[param]} except ValidationError, e: return {"success": False, "message": e}
def parse_comment(comment): """ Parse the comment for users and hashes, and generate html. HTML is escaped prior to parsing out users and tags. :param comment: The comment to parse. :type comment: str :returns: dict with keys "users", "tags", and "html" """ re_user = re.compile(r"@[0-9a-zA-Z+_]*", re.IGNORECASE) re_tag = re.compile(r"#[0-9a-zA-Z+_]*", re.IGNORECASE) c = {"users": [], "tags": [], "html": ""} users = [] tags = [] # escape for safety # from https://wiki.python.org/moin/EscapingHtml comment = "".join({"&": "&", '"': """, "'": "'", ">": ">", "<": "<"}.get(c, c) for c in comment) # get users for i in re_user.finditer(comment): user = i.group(0).replace("@", "").strip() if len(user) and CRIPTsUser.objects(username=user).count() == 1: users.append(user) # dedupe users = list(set(users)) c["users"] = users # get tags for i in re_tag.finditer(comment): tag = i.group(0).replace("#", "").strip() if len(tag): tags.append(tag) # dedupe tags = list(set(tags)) c["tags"] = tags # generate html for user in users: link = '<a href="%s" class="comment_link">@%s</a>' % ( reverse("cripts.comments.views.activity", args=["byuser", user]), user, ) comment = comment.replace("@%s" % user, link) for tag in tags: link = '<a href="%s" class="comment_link">#%s</a>' % ( reverse("cripts.comments.views.activity", args=["bytag", tag]), tag, ) comment = comment.replace("#%s" % tag, link) c["html"] = comment return c
def AddUser(self): self.user = CRIPTsUser.create_user(username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL, ) self.assertEqual(self.user.username, TUSER_NAME) self.assertTrue(TUSER_PASS_HASH_RE.match(self.user.password)) self.user.first_name = TUSER_FNAME self.user.last_name = TUSER_LNAME self.user.save()
def toggle_user_preference(username, section, setting, is_enabled=False): """ Enables/Disables the target user preference :param username: The username that the preference toggle is for. :type username: str :param section: The section name where the preference is stored. :type section: str :param setting: The name of the setting within the section of the preference. :type setting: str :param is_enabled: An optional default value if the preference does not exist. :type is_enabled: str :returns: "success" (boolean), "message" (str) if failed, "state" (boolean) if successful """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: # Split the preference option into subtrees on '.' otree = setting.split(".") param = otree.pop() if not section in user.prefs: setattr(user.prefs, section, {}) opt = user.prefs[section] if len(otree): for subsect in otree: if not subsect in opt: opt[subsect] = {} opt = opt[subsect] else: opt = opt[subsect] if (not param in opt): # if the preference doesn't exist, then try the fallback default value if is_enabled == True: opt[param] = False else: opt[param] = True else: # the preference exists, so use it if (not opt[param]): opt[param] = True else: opt[param] = False try: user.save() return {'success': True, 'state': opt[param]} except ValidationError, e: return {'success': False, 'message': e}
def AddUser(self): self.user = CRIPTsUser.create_user( username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL, ) self.assertEqual(self.user.username, TUSER_NAME) self.assertTrue(TUSER_PASS_HASH_RE.match(self.user.password)) self.user.first_name = TUSER_FNAME self.user.last_name = TUSER_LNAME self.user.save()
def get_user_subscriptions(username): """ Get user subscriptions. :param username: The user to query for. :type username: str :returns: list """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() return user.subscriptions
def get_user_email_notification(username): """ Get user email notification preference. :param username: The user to query for. :type username: str :returns: str """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() return user.get_preference('notify', 'email', False)
def get_user_role(username): """ Get the user role. :param username: The user to lookup. :type username: str :returns: str """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() return user.role
def get_user_email_notification(username): """ Get user email notification preference. :param username: The user to query for. :type username: str :returns: str """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() return user.get_preference("notify", "email", False)
def clean_db(): """ Clean up the DB after testing. """ src = SourceAccess.objects(name=TSRC).first() if src: src.delete() user = CRIPTsUser.objects(username=TUSER_NAME).first() if user: user.delete() TestObject.drop_collection() TestSourceObject.drop_collection() CRIPTsConfig.drop_collection()
def get_user_info(username=None): """ Get information for a specific user. :param username: The user to get info for. :type username: str :returns: :class:`cripts.core.user.CRIPTsUser` """ from cripts.core.user import CRIPTsUser if username is not None: username = str(username) return CRIPTsUser.objects(username=username).first() else: return username
def get_user_list(): """ Get a list of users. Sort the list alphabetically and do not include subscriptions. :returns: list """ from cripts.core.user import CRIPTsUser users = CRIPTsUser.objects().order_by('+username').exclude('subscriptions') user_list = [] user_list.append({'username': "", 'sources': [], 'role': ""}) for user in users: user_list.append(user) return user_list
def is_admin(username): """ Determine if the user is an admin. :param username: The user to lookup. :type username: str :returns: True, False """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: if user.role == "Administrator": return True return False
def get_user_list(): """ Get a list of users. Sort the list alphabetically and do not include subscriptions. :returns: list """ from cripts.core.user import CRIPTsUser users = CRIPTsUser.objects().order_by("+username").exclude("subscriptions") user_list = [] user_list.append({"username": "", "sources": [], "role": ""}) for user in users: user_list.append(user) return user_list
def get_user_organization(username): """ Get the organization for a user. :param username: The user to lookup. :type username: str :returns: str """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: return user.organization else: return settings.COMPANY_NAME
def revoke_api_key_by_name(username, name): """ Revoke API key by the name. :param username: The user to search for. :type username: str :param name: The name of the API key. :type name: str :returns: dict with keys "success" (boolean) and "message" (str) """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: return user.revoke_api_key(name, username) return {'success': False, 'message': 'No user to revoke key for.'}
def get_api_key_by_name(username, name): """ Get a user's API key by the name. :param username: The user to search for. :type username: str :param name: The name of the API key. :type name: str :returns: str, None """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: return user.get_api_key(name) return None
def revoke_api_key_by_name(username, name): """ Revoke API key by the name. :param username: The user to search for. :type username: str :param name: The name of the API key. :type name: str :returns: dict with keys "success" (boolean) and "message" (str) """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: return user.revoke_api_key(name, username) return {"success": False, "message": "No user to revoke key for."}
def toggle_active(username, analyst): """ Toggle a user active/inactive. :param username: The user to query for. :type username: str :param analyst: The user toggling this user active/inactive. :type analyst: str """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if user: if user.is_active: user.mark_inactive(analyst=analyst) else: user.mark_active(analyst=analyst)
def is_user_subscribed_to_source(username, source): """ Determine if the user is subscribed to this source. :param username: The user to query for. :type username: str :param source: The source name. :type source: str :returns: boolean """ from cripts.core.user import CRIPTsUser username = str(username) query = {'username': username, 'subscriptions.Source.name': source} results = CRIPTsUser.objects(__raw__=query).first() if results is not None: return True else: return False
def is_user_subscribed_to_source(username, source): """ Determine if the user is subscribed to this source. :param username: The user to query for. :type username: str :param source: The source name. :type source: str :returns: boolean """ from cripts.core.user import CRIPTsUser username = str(username) query = {"username": username, "subscriptions.Source.name": source} results = CRIPTsUser.objects(__raw__=query).first() if results is not None: return True else: return False
def change_user_password(username, current_p, new_p, new_p_c): """ Change the password for a user. :param username: The user to query for. :type username: str :param current_p: The user's current password. :type current_p: str :param new_p: The new password. :type new_p: str :param new_p_c: New password confirmation. :type new_p_c: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ if new_p != new_p_c: return { 'success': False, 'message': 'New password confirmation does not match.' } from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if not user: return {'success': False, 'message': 'Unknown user.'} if not user.check_password(current_p): return {'success': False, 'message': 'Current password invalid.'} if user.set_password(new_p, username): return {'success': True, 'message': 'Password Change Successful.'} else: from cripts.config.config import CRIPTsConfig cripts_config = CRIPTsConfig.objects().first() if cripts_config: regex_desc = cripts_config.password_complexity_desc else: regex_desc = settings.PASSWORD_COMPLEXITY_DESC return { 'success': False, 'message': 'Password not complex enough: %s' % regex_desc }
def save_user_secret(username, totp_pass, title, size): """ Save the TOTP secret for a user. If we can generate a QRCode for them to scan off the screen, we will return that as well. :param username: The user to save the secret for. :type username: str :param totp_pass: The secret to save. :type totp_pass: str :param title: The title for the QRCode. :type title: str :param size: The size of the QRCode image. :type size: tuple. :returns: dict with keys: "success" (boolean), "secret" (str), "qr_img" (str or None) """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() response = {} if user: (crypt_secret, totp_secret) = gen_user_secret(totp_pass, username) user.secret = crypt_secret user.totp = True user.save() response['success'] = True response['secret'] = totp_secret qr_img = generate_qrcode( "otpauth://totp/%s?secret=%s" % (title, totp_secret), size) if qr_img: response['qr_img'] = qr_img else: response['qr_img'] = None else: response['success'] = False return response
def save_user_secret(username, totp_pass, title, size): """ Save the TOTP secret for a user. If we can generate a QRCode for them to scan off the screen, we will return that as well. :param username: The user to save the secret for. :type username: str :param totp_pass: The secret to save. :type totp_pass: str :param title: The title for the QRCode. :type title: str :param size: The size of the QRCode image. :type size: tuple. :returns: dict with keys: "success" (boolean), "secret" (str), "qr_img" (str or None) """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() response = {} if user: (crypt_secret, totp_secret) = gen_user_secret(totp_pass, username) user.secret = crypt_secret user.totp = True user.save() response["success"] = True response["secret"] = totp_secret qr_img = generate_qrcode("otpauth://totp/%s?secret=%s" % (title, totp_secret), size) if qr_img: response["qr_img"] = qr_img else: response["qr_img"] = None else: response["success"] = False return response
def get_subscribed_users(stype, oid, sources): """ Get users subscribed to this top-level object. :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: list :param sources: A list of sources of the top-level object. :type sources: list :returns: list """ from cripts.core.user import CRIPTsUser user_list = [] query = {"$or": [{"subscriptions.%s.id" % stype: ObjectId(oid)}, {"subscriptions.Source.name": {"$in": sources}}]} users = CRIPTsUser.objects(__raw__=query) for user in users: user_list.append(user.username) return user_list
def user_sources(username): """ Get the sources for a user. :param username: The user to lookup. :type username: str :returns: list """ if username: from cripts.core.user import CRIPTsUser username = str(username) try: user = CRIPTsUser.objects(username=username).first() if user: return user.sources else: return [] except Exception: return [] else: return []
def is_user_subscribed(username, stype, oid): """ Determine if the user is subscribed to this top-level object. :param username: The user to query for. :type username: str :param stype: The top-level object type. :type stype: str :param oid: The ObjectId of the top-level object. :type oid: str :returns: boolean """ from cripts.core.user import CRIPTsUser username = str(username) query = {"username": username, "subscriptions.%s.id" % stype: ObjectId(oid)} results = CRIPTsUser.objects(__raw__=query).first() if results is not None: return True else: return False
def is_user_favorite(analyst, type_, id_): """ Check if an ID is in a user's favorites. :param analyst: The username. :type analyst: str :param type_: The type of the object. :type type_: str :param id_: The ID of the object. :type id_: str :returns: boolean """ if analyst: from cripts.core.user import CRIPTsUser user = CRIPTsUser.objects(username=analyst).first() if not user: return False if type_ in user.favorites: if str(id_) in user.favorites[type_]: return True return False
def subscribe_to_source(username, source): """ Subscribe a user to a source. :param username: The user to query for. :type username: str :param source: The name of the source. :type source: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import EmbeddedSourceSubscription from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() es = EmbeddedSourceSubscription() es.name = source user.subscriptions['Source'].append(es) try: user.save() return {'success': True} except ValidationError, e: return {'success': False, 'message': e}
def unsubscribe_from_source(username, source): """ Unsubscribe a user from a source. :param username: The user to query for. :type username: str :param source: The name of the source. :type source: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() for s in user.subscriptions['Source']: if s.name == source: user.subscriptions['Source'].remove(s) break try: user.save() return {'success': True} except ValidationError, e: return {'success': False, 'message': e}
def prep_db(): """ Prep the DB for testing. """ clean_db() # Create a new default config cripts_config = CRIPTsConfig() cripts_config.save() # Add Source handlers.add_new_source(TSRC, TRANDUSER) # Add User user = CRIPTsUser.create_user( username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL, ) user.first_name = TUSER_FNAME user.last_name = TUSER_LNAME user.save() # Add test source object obj = TestSourceObject() obj.name = TOBJS_NAME obj.value = TOBJS_VALUE obj.add_source(source=TSRC, analyst=TUSER_NAME) obj.save() # Add another with Different source obj = TestSourceObject() obj.name = TOBJS_NAME obj.value = TOBJS_VALUE obj.add_source(source=TUNKSRC, analyst=TRANDUSER) obj.save() # Add test non-source object obj = TestObject() obj.name = TOBJ_NAME obj.value = TOBJ_VALUE obj.save()
def is_authenticated(self, request, **kwargs): """ Determine if the user can properly authenticate with the username and API key they provided. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :returns: True, :class:`tastypie.http.HttpUnauthorized` """ try: username, api_key = self.extract_credentials(request) except ValueError: return self._unauthorized() if not username or not api_key: return self._unauthorized() try: from cripts.core.user import CRIPTsUser user = CRIPTsUser.objects(username=username).first() except: return self._unauthorized() if not user: return self._unauthorized() if not user.is_active: return self._unauthorized() key_auth_check = self.get_key(user, api_key) if key_auth_check: request.user = user return True else: return self._unauthorized()
def prep_db(): """ Prep the DB for testing. """ clean_db() # Create a new default config cripts_config = CRIPTsConfig() cripts_config.save() # Add Source handlers.add_new_source(TSRC, TRANDUSER) # Add User user = CRIPTsUser.create_user(username=TUSER_NAME, password=TUSER_PASS, email=TUSER_EMAIL, ) user.first_name = TUSER_FNAME user.last_name = TUSER_LNAME user.save() # Add test source object obj = TestSourceObject() obj.name = TOBJS_NAME obj.value = TOBJS_VALUE obj.add_source(source=TSRC, analyst=TUSER_NAME) obj.save() # Add another with Different source obj = TestSourceObject() obj.name = TOBJS_NAME obj.value = TOBJS_VALUE obj.add_source(source=TUNKSRC, analyst=TRANDUSER) obj.save() # Add test non-source object obj = TestObject() obj.name = TOBJ_NAME obj.value = TOBJ_VALUE obj.save()
def unsubscribe_from_source(username, source): """ Unsubscribe a user from a source. :param username: The user to query for. :type username: str :param source: The name of the source. :type source: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() for s in user.subscriptions["Source"]: if s.name == source: user.subscriptions["Source"].remove(s) break try: user.save() return {"success": True} except ValidationError, e: return {"success": False, "message": e}
def change_user_password(username, current_p, new_p, new_p_c): """ Change the password for a user. :param username: The user to query for. :type username: str :param current_p: The user's current password. :type current_p: str :param new_p: The new password. :type new_p: str :param new_p_c: New password confirmation. :type new_p_c: str :returns: dict with keys "success" (boolean) and "message" (str) if failed. """ if new_p != new_p_c: return {"success": False, "message": "New password confirmation does not match."} from cripts.core.user import CRIPTsUser username = str(username) user = CRIPTsUser.objects(username=username).first() if not user: return {"success": False, "message": "Unknown user."} if not user.check_password(current_p): return {"success": False, "message": "Current password invalid."} if user.set_password(new_p, username): return {"success": True, "message": "Password Change Successful."} else: from cripts.config.config import CRIPTsConfig cripts_config = CRIPTsConfig.objects().first() if cripts_config: regex_desc = cripts_config.password_complexity_desc else: regex_desc = settings.PASSWORD_COMPLEXITY_DESC return {"success": False, "message": "Password not complex enough: %s" % regex_desc}