def setUp(self):
     a = Account()
     a._commit()
     sr = Subreddit(name = 'subreddit_name_%s' % (self.seconds_since_epoc(),),
                    title = 'subreddit_title_%s' % (self.seconds_since_epoc(),),)
     sr._commit()
     self.rel = SRMember(sr, a, 'test')
Example #2
0
    def _developers(self):
        """Returns a list of users who are developers of this client."""

        devs = Account._byID(list(self._developer_ids))
        return [
            dev for dev in devs.itervalues() if not (dev._deleted or dev._spam)
        ]
Example #3
0
 def get_editor_accounts(self):
     editors = self.get_editors()
     accounts = [Account._byID36(editor, data=True)
                 for editor in self.get_editors()]
     accounts = [account for account in accounts
                 if not account._deleted]
     return accounts
Example #4
0
 def get_editor_accounts(self):
     editors = self.get_editors()
     accounts = [Account._byID36(editor, data=True)
                 for editor in self.get_editors()]
     accounts = [account for account in accounts
                 if not account._deleted]
     return accounts
Example #5
0
    def GET_refresh_token(self, *args, **kwargs):  # pylint: disable=unused-argument
        """Generate a refresh token given a username"""
        username = request.GET['username']
        try:
            account = Account._by_name(username)
        except NotFound:
            account = register(username, uuid4().hex, '127.0.0.1')

        # subscribe the user now because reddit does not have consistency across
        # its APIs on what it considers the user to be subscribed to
        if not account.has_subscribed:
            Subreddit.subscribe_defaults(account)
            account.has_subscribed = True
            account._commit()

        client_id = g.secrets['generate_refresh_token_client_id']
        client = OAuth2Client.get_token(client_id)
        scope = OAuth2Scope(OAuth2Scope.FULL_ACCESS)
        user_id = account._id36
        refresh_token = OAuth2RefreshToken._new(
            client_id=client._id,
            user_id=user_id,
            scope=scope,
        )
        access_token = OAuth2AccessToken._new(
            client_id=client._id,
            user_id=user_id,
            scope=scope,
            device_id='device',
        )
        return json.dumps(OAuth2AccessController._make_new_token_response(access_token, refresh_token))
Example #6
0
    def check_valid(self):
        """Returns boolean indicating whether or not this access token is still valid."""

        # Has the token been revoked?
        if getattr(self, 'revoked', False):
            return False

        # Is the OAuth2Client still valid?
        try:
            client = OAuth2Client._byID(self.client_id)
            if getattr(client, 'deleted', False):
                raise NotFound
        except NotFound:
            return False

        # Is the user account still valid?
        if self.user_id:
            try:
                account = Account._byID36(self.user_id)
                if account._deleted:
                    raise NotFound
            except NotFound:
                return False

        return True
Example #7
0
def get_author_name(author_name):
    if not author_name:
        return "[unknown]"
    try:
        return Account._by_name(author_name).name
    except NotFound:
        return '[deleted]'
Example #8
0
def get_author_name(author_name):
    if not author_name:
        return "[unknown]"
    try:
        return Account._by_name(author_name).name
    except NotFound:
        return "[deleted]"
Example #9
0
 def revoke(self):
     super(OAuth2RefreshToken, self).revoke()
     account = Account._byID36(self.user_id)
     access_tokens = OAuth2AccessToken._by_user(account)
     for token in access_tokens:
         if token.refresh_token == self._id:
             token.revoke()
Example #10
0
    def _copy_multi(self, from_multi, to_path_info):
        self._check_new_multi_path(to_path_info)

        to_owner = Account._by_name(to_path_info["username"])

        try:
            LabeledMulti._byID(to_path_info["path"])
        except tdb_cassandra.NotFound:
            to_multi = LabeledMulti.copy(to_path_info["path"], from_multi, owner=to_owner)
        else:
            raise RedditError("MULTI_EXISTS", code=409, fields="multipath")

        return to_multi
Example #11
0
    def _copy_multi(self, from_multi, to_path_info):
        self._check_new_multi_path(to_path_info)

        to_owner = Account._by_name(to_path_info['username'])

        try:
            LabeledMulti._byID(to_path_info['path'])
        except tdb_cassandra.NotFound:
            to_multi = LabeledMulti.copy(to_path_info['path'], from_multi,
                                         owner=to_owner)
        else:
            raise RedditError('MULTI_EXISTS', code=409, fields='multipath')

        return to_multi
Example #12
0
    def get_participant_account(self):
        if self.is_internal:
            return None

        try:
            convo_participant = ModmailConversationParticipant.get_participant(
                self.id)
            participant = Account._byID(convo_participant.account_id)
        except NotFound:
            if not self.is_auto:
                raise
            return None

        if participant._deleted:
            raise NotFound

        return participant
Example #13
0
    def top_promoters(cls, start_date, end_date = None):
        end_date = end_date or datetime.datetime.now(g.tz)
        q = cls.for_date_range(start_date, end_date)

        d = start_date
        res = []
        accounts = Account._byID([i.account_id for i in q],
                                 return_dict = True, data = True)
        res = {}
        for i in q:
            if i.bid is not None and i.actual_start is not None:
                r = res.setdefault(i.account_id, [0, 0, set()])
                r[0] += i.bid
                r[1] += i.refund
                r[2].add(i.thing_name)
        res = [ ([accounts[k]] + v) for (k, v) in res.iteritems() ]
        res.sort(key = lambda x: x[1] - x[2], reverse = True)

        return res
Example #14
0
    def top_promoters(cls, start_date, end_date=None):
        end_date = end_date or datetime.datetime.now(g.tz)
        q = cls.for_date_range(start_date, end_date)

        d = start_date
        res = []
        accounts = Account._byID([i.account_id for i in q],
                                 return_dict=True,
                                 data=True)
        res = {}
        for i in q:
            if i.bid is not None and i.actual_start is not None:
                r = res.setdefault(i.account_id, [0, 0, set()])
                r[0] += i.bid
                r[1] += i.refund
                r[2].add(i.thing_name)
        res = [([accounts[k]] + v) for (k, v) in res.iteritems()]
        res.sort(key=lambda x: x[1] - x[2], reverse=True)

        return res
Example #15
0
    def check_valid(self):
        if getattr(self, 'revoked', False):
            return False

        try:
            client = OAuth2Client._byID(self.client_id)
            if getattr(client, 'deleted', False):
                raise NotFound
        except AttributeError:
            g.log.error("bad token %s: %s", self, self._t)
            raise
        except NotFound:
            return False

        if self.user_id:
            try:
                account = Account._byID36(self.user_id)
                if account._deleted:
                    raise NotFound
            except NotFound:
                return False

        return True
Example #16
0
    def check_valid(self):
        if getattr(self, 'revoked', False):
            return False

        try:
            client = OAuth2Client._byID(self.client_id)
            if getattr(client, 'deleted', False):
                raise NotFound
        except AttributeError:
            g.log.error("bad token %s: %s", self, self._t)
            raise
        except NotFound:
            return False

        if self.user_id:
            try:
                account = Account._byID36(self.user_id)
                if account._deleted:
                    raise NotFound
            except NotFound:
                return False

        return True
Example #17
0
def update_sr_mods_modmail_icon(sr):
    """Helper method to set the modmail icon for mods with mail permissions
    for the passed sr.

    Method will lookup all moderators for the passed sr and query whether they
    have unread conversations that exist. If the user has unreads the modmail
    icon will be lit up, if they do not it will be disabled.

    Args:
    sr  -- Subreddit object to fetch mods with mail perms from
    """

    mods_with_perms = sr.moderators_with_perms()
    modmail_user_ids = [mod_id for mod_id, perms in mods_with_perms.iteritems()
                        if 'mail' in perms or 'all' in perms]

    mod_accounts = Account._byID(modmail_user_ids, ignore_missing=True,
                                 return_dict=False)

    mail_exists_by_user = (ModmailConversationUnreadState
                           .users_unreads_exist(mod_accounts))

    for mod in mod_accounts:
        set_modmail_icon(mod, bool(mail_exists_by_user.get(mod._id)))
Example #18
0
    def to_serializable(self, author=None):
        if not author:
            from r2.models import Account
            author = Account._byID(self.account_id)

        name = author.name
        author_id = author._id
        if author._deleted:
            name = '[deleted]'
            author_id = None

        return {
            'id': to36(self.id),
            'author': {
                'id': author_id,
                'name': name,
                'isAdmin': author.employee,
                'isMod': True,
                'isHidden': False,
                'isDeleted': author._deleted
            },
            'actionTypeId': self.action_type_id,
            'date': self.date.isoformat(),
        }
Example #19
0
# Initialise a newly-created db with required tables, users,
# categories and tags.
from r2.lib.db.thing import NotFound
from r2.models.account import Account, AccountExists, register
from r2.models.link import Tag, TagExists
from r2.models.subreddit import Subreddit

try:
    register('admin', 'swordfish', '')
except AccountExists:
    pass

admin = Account._by_name('admin')
admin.email_validated = True
admin._commit()

try:
    Subreddit._by_name('admin')
except NotFound:
    Subreddit._create_and_subscribe('admin', admin,
                                    { 'title': 'Admin',
                                      'type': 'restricted',
                                      'default_listing': 'new' })

try:
    Subreddit._by_name('main')
except NotFound:
    Subreddit._create_and_subscribe('main', admin,
                                    { 'title': 'EA Forum',
                                      'type': 'restricted',
                                      'default_listing': 'new' })
Example #20
0
 def is_first_party(self):
     return self.has_developer(Account.system_user())
Example #21
0
    def _developers(self):
        """Returns a list of users who are developers of this client."""

        devs = Account._byID(list(self._developer_ids), return_dict=False)
        return [dev for dev in devs if not dev._deleted]
Example #22
0
# Initialise a newly-created db with required tables, users,
# categories and tags.
from r2.lib.db.thing import NotFound
from r2.models.account import Account, AccountExists, register
from r2.models.link import Tag, TagExists
from r2.models.subreddit import Subreddit

try:
    register('admin', 'swordfish', '', False)
except AccountExists:
    pass

admin = Account._by_name('admin')
admin.email_validated = True
admin._commit()

try:
    Subreddit._by_name('main')
except NotFound:
    Subreddit._create_and_subscribe(
        'main', admin, {
            'title': 'Effective Altruism Forum',
            'type': 'restricted',
            'default_listing': 'new'
        })

try:
    Subreddit._by_name('admin')
except NotFound:
    Subreddit._create_and_subscribe('admin', admin, {
        'title': 'Admin',
Example #23
0
 def setUp(self):
     a = Account()
     a._id = 1
     sr = Subreddit()
     sr._id = 2
     self.rel = SRMember(sr, a, 'test')
Example #24
0
    def _developers(self):
        """Returns a list of users who are developers of this client."""

        devs = Account._byID(list(self._developer_ids), return_dict=False)
        return [dev for dev in devs if not dev._deleted]
Example #25
0
File: wiki.py Project: wal-f/reddit
 def get_author(self):
     author = self._get('author')
     return Account._byID36(author, data=True) if author else None
Example #26
0
File: wiki.py Project: wal-f/reddit
 def get_author(self):
     if self._get('last_edit_by'):
         return Account._byID36(self.last_edit_by, data=True)
     return None
Example #27
0
File: wiki.py Project: wal-f/reddit
 def get_authors(cls, revisions):
     authors = [r._get('author') for r in revisions]
     authors = filter(None, authors)
     return Account._byID36(authors, data=True)
Example #28
0
# Initialise a newly-created db with required tables, users,
# categories and tags.
from r2.lib.db.thing import NotFound
from r2.models.account import Account, AccountExists, register
from r2.models.link import Tag, TagExists
from r2.models.subreddit import Subreddit

try:
    register("admin", "swordfish", "", False)
except AccountExists:
    pass

admin = Account._by_name("admin")
admin.email_validated = True
admin._commit()

try:
    Subreddit._by_name("lesswrong")
except NotFound:
    Subreddit._create_and_subscribe(
        "lesswrong", admin, {"title": "Less Wrong", "type": "restricted", "default_listing": "blessed"}
    )

try:
    Subreddit._by_name("discussion")
except NotFound:
    s = Subreddit._create_and_subscribe(
        "discussion", admin, {"title": "Less Wrong Discussion", "type": "public", "default_listing": "new"}
    )
    s.header = "/static/logo-discussion.png"
    s.stylesheet = "/static/discussion.css"
Example #29
0
 def setUp(self):
     a = Account()
     a._commit()
     sr = Subreddit()
     sr._commit()
     self.rel = SRMember(sr, a, 'test')
Example #30
0
 def is_first_party(self):
     return self.has_developer(Account.system_user())
Example #31
0
 def get_author(self):
     if self._get('last_edit_by'):
         return Account._byID36(self.last_edit_by, data=True)
     return None
Example #32
0
 def valid_for_credentials(self, email, password):
     user = Account._by_fullname(self.user_id)
     return (self.email_address.lower() == email.lower() and
             valid_password(user, password, self.password))
Example #33
0
 def valid_for_credentials(self, email, password):
     user = Account._by_fullname(self.user_id)
     return (self.email_address.lower() == email.lower()
             and valid_password(user, password, self.password))
Example #34
0
    def _developers(self):
        """Returns a list of users who are developers of this client."""

        devs = Account._byID(list(self._developer_ids))
        return [dev for dev in devs.itervalues()
                if not (dev._deleted or dev._spam)]
Example #35
0
 def get_author(self):
     author = self._get('author')
     return Account._byID36(author, data=True) if author else None
Example #36
0
 def get_authors(cls, revisions):
     authors = [r._get('author') for r in revisions]
     authors = filter(None, authors)
     return Account._byID36(authors, data=True)
Example #37
0
    def to_serializable(self, authors_dict=None, entity=None,
                        all_messages=False, current_user=None):
        # Lookup authors if they are not passed
        if not authors_dict:
            from r2.models import Account
            authors_dict = Account._byID(
                    set(self.author_ids) | set(self.mod_action_account_ids),
                    return_dict=True)

        # Lookup entity if it is not passed
        if not entity:
            entity = Subreddit._by_fullname(self.owner_fullname)

        serializable_authors = []

        for message in self.messages:
            author = authors_dict.get(message.author_id)
            serializable_authors.append(
                to_serializable_author(author, entity,
                                       current_user,
                                       is_hidden=message.is_author_hidden)
            )

        last_unread = getattr(self, 'last_unread', None)
        if last_unread is not None:
            last_unread = last_unread.isoformat()

        parsed_last_user_update = None
        parsed_last_mod_update = None

        min_tz_aware_datetime = datetime.min.replace(tzinfo=g.tz)
        if self.last_user_update != min_tz_aware_datetime:
            parsed_last_user_update = self.last_user_update.isoformat()

        if self.last_mod_update != min_tz_aware_datetime:
            parsed_last_mod_update = self.last_mod_update.isoformat()

        result_dict = {
            'state': self.state,
            'lastUpdated': self.last_updated.isoformat(),
            'lastUserUpdate': parsed_last_user_update,
            'lastModUpdate': parsed_last_mod_update,
            'lastUnread': last_unread,
            'isInternal': self.is_internal,
            'isAuto': self.is_auto,
            'numMessages': self.num_messages,
            'owner': {
                'id': self.owner_fullname,
                'type': entity._type_name,
                'displayName': entity.name
            },
            'isHighlighted': self.is_highlighted,
            'id': to36(self.id),
            'subject': self.subject,
            'authors': serializable_authors,
        }

        if all_messages:
            for mod_action in self.mod_actions:
                author = authors_dict.get(mod_action.account_id)
                serializable_authors.append(
                    to_serializable_author(author, entity,
                                           current_user,
                                           is_hidden=False)
                )

            result_dict.update({
                'objIds': self.ordered_msg_and_action_ids,
                'messages': {
                    to36(message.id): message.to_serializable(
                        entity,
                        authors_dict.get(message.author_id),
                        current_user
                    )
                    for message in self.messages
                },
                'modActions': {
                    to36(mod_action.id): mod_action.to_serializable()
                    for mod_action in self.mod_actions
                }
            })
        else:
            result_dict.update({
                'objIds': [
                    {'key': 'messages', 'id': to36(self.messages[0].id)}
                ]
            })

        return result_dict