예제 #1
0
    def authenticate(self, request):
        email = request.user_email
        validate_email(email)
        team_key = request.team_key
        user = User.find_user_by_email(email, team_key)

        if team_key:
            team_secret = request.team_secret
            validate_team_secret(team_secret)

            display_name = request.display_name
            image_url = request.user_image_url

            if not user:
                user = User.insert_user(email=email, username=display_name, account_type=team_key, image_url=image_url)
                community = Community.getCommunityFromTeamKey(team_key)
                UserRole.insert(user, community)
            elif (display_name != user.display_name) or (image_url != user.image_url):
                User.update_user(user=user, email=email, username=display_name, account_type=team_key, image_url=image_url)
            if not Community.authenticate(team_key, md5(team_secret)):
                raise endpoints.UnauthorizedException("Authentication failed. Team key and secret are not matched.")
        elif user.auth_source == AuthSourceType.ANNO:
            password = request.password
            validate_password(password)
            if not user:
                raise endpoints.NotFoundException("Authentication failed. User account " + email + " doesn't exist.")
            if not User.authenticate(email, md5(password)):
                raise endpoints.UnauthorizedException("Authentication failed. Email and password are not matched.")
        else:
            raise endpoints.ForbiddenException("Account for '%s' is Google or Facebook OAuth account." % email)

        return UserMessage(id=user.key.id(), display_name=user.display_name)
예제 #2
0
파일: user_api.py 프로젝트: usersource/anno
    def community_users(self, request):
        user = auth_user(self.request_state.headers)
        community_userroles = []

        if user:
            community = Community.getCommunityFromTeamKey(request.account_type)
            if community and (UserRole.getCircleLevel(user, community) > 0):
                community_userroles = UserRole.query().filter(ndb.AND(UserRole.community == community.key,
                                                                      UserRole.circle_level > 0)
                                                              ).fetch(projection=[UserRole.user])

        users = []
        for community_userrole in community_userroles:
            current_user = community_userrole.user.get()
            users.append(UserMessage(id=current_user.key.id(),
                                     user_email=current_user.user_email,
                                     display_name=current_user.display_name,
                                     image_url=current_user.image_url))

        # removing auth_user
        [ users.remove(user_info) for user_info in users if user_info.user_email == user.user_email ]

        # sorting users alphabetically
        users = sorted(users, key=lambda user_info: user_info.display_name.lower())

        return UserListMessage(user_list=users)
예제 #3
0
파일: utils.py 프로젝트: usersource/anno
def isMember(community, user, include_manager=True):
    if include_manager:
        query = UserRole.query(ndb.AND(UserRole.community == community.key,
                                       UserRole.user == user.key)
                               )
    else:
        query = UserRole.query(ndb.AND(UserRole.community == community.key,
                                       UserRole.user == user.key,
                                       UserRole.role == UserRoleType.MEMBER)
                               )

    results = query.get()
    return True if results else False
예제 #4
0
    def delete_user(self, request):
        user = get_user_from_request(user_id=request.user_id, user_email=request.user_email)
        community = Community.get_by_id(request.community_id)
        success = False

        if community:
            if user:
                UserRole.delete(user, community)
                success = True
            elif request.include_invite:
                Invite.delete(request.user_email, community)
                success = True

        return ResponseMessage(success=success)
예제 #5
0
    def dashboard_authenticate(self, request):
        email = request.user_email
        password = request.password
        team_key = request.team_key

        accounts = []
        if email and password:
            users = User.get_all_user_by_email(email, md5(password), team_key=team_key)

            for user in users:
                if user:
                    team_key = user.account_type
                    team = Community.getCommunityFromTeamKey(team_key)
                    if team:
                        userTeamToken = get_user_team_token(email, password, team_key,
                                                            team.team_secret, user.display_name,
                                                            user.image_url)
                        account = AccountAuthenticateMessage(display_name=user.display_name,
                                                             image_url=user.image_url,
                                                             team_name=team.name,
                                                             team_key=team_key,
                                                             team_hash=team.team_hash,
                                                             user_team_token=json.dumps(userTeamToken),
                                                             role=UserRole.getRole(user, team))
                        accounts.append(account)

        return AccountAuthenticateListMessage(authenticated=True if len(accounts) else False, account_info=accounts)
예제 #6
0
def create_teams():
    team_key = ""
    app_name = ""
    community_name = ""
    admin_user_email = ""
    other_users_email = []

    app = AppInfo.query().filter(AppInfo.lc_name == app_name.lower()).get()
    if not app:
        appinfo_message = AppInfoMessage()
        appinfo_message.name = app_name
        app = AppInfo.insert(appinfo_message)

    community = Community.getCommunityFromTeamKey(team_key=team_key)
    if not community:
        community_message = CommunityMessage(name=community_name,
                                             team_key=team_key,
                                             team_secret=md5(community_name.lower()))
        community_message.user = UserMessage(user_email=admin_user_email)
        Community.insert(community_message)
        community = Community.getCommunityFromTeamKey(team_key=team_key)

    if community and app:
        if not app.key in community.apps:
            community.apps.append(app.key)
            community.put()

    for user_email in other_users_email:
        user = User.find_user_by_email(email=user_email, team_key=team_key)
        if not user:
            user = User.insert_user(user_email, account_type=team_key, image_url="")
        userrole = UserRole.insert(user, community)
예제 #7
0
    def get_circle_users(self, request):
        roles = [UserRoleType.MEMBER, UserRoleType.ADMIN]
        community = Community.getCommunityFromTeamKey(request.team_key)

        circle_list_message = []
        for circle_value, circle_name in community.circles.items():
            circle_message = CommunityCircleMembersMessage()
            circle_message.circle_name = circle_name
            circle_message.users = []

            for userrole in UserRole.getUsersByCircle(community.key, int(circle_value)):
                user = userrole.user.get()
                if user and (user.account_type == community.team_key):
                    if user.user_email.split("@")[1] == "devnull.usersource.io":
                        break

                    user_message = UserAdminMasterMessage()
                    user_message.display_name = user.display_name
                    user_message.user_email = user.user_email
                    user_message.password_present = True if user.password else False
                    user_message.role = userrole.role
                    user_message.image_url = user.image_url
                    circle_message.users.append(user_message)

            circle_list_message.append(circle_message)

        return CommunityCircleMembersListMessage(circle_list=circle_list_message, roles=roles)
예제 #8
0
    def update_user(self, request):
        action_auth_user = auth_user(self.request_state.headers)
        if not (action_auth_user.user_email == request.user_email):
            if not is_auth_user_admin(action_auth_user=action_auth_user):
                return ResponseMessage(success=False)

        user = get_user_from_request(user_id=request.user_id,
                                     user_email=request.user_email,
                                     team_key=request.team_key)

        if user:
            user.display_name = request.user_display_name or user.display_name
            user.password = md5(request.user_password) if request.user_password else user.password
            user.image_url = request.user_image_url or user.image_url or ""
            user.put()

        community = Community.getCommunityFromTeamKey(request.team_key) if request.team_key else Community.get_by_id(request.community_id)

        resp = None
        if user and community:
            circle = 0
            for circle_value, circle_name in community.circles.iteritems():
                if circle_name == request.circle:
                    circle = int(circle_value)

            resp = UserRole.edit(user, community, request.role, circle)

        return ResponseMessage(success=True if resp else False)
예제 #9
0
    def insert_user(self, request):
        if not is_auth_user_admin(headers=self.request_state.headers):
            return ResponseMessage(success=False)

        action_user = auth_user(self.request_state.headers)
        user = get_user_from_request(user_id=request.user_id,
                                     user_email=request.user_email,
                                     team_key=request.team_key)

        if not user:
            user = User.insert_user(request.user_email,
                                    username=request.user_display_name,
                                    account_type=request.team_key,
                                    auth_source=AuthSourceType.PLUGIN,
                                    password=md5(request.user_password),
                                    image_url=request.user_image_url or "")

        community = Community.getCommunityFromTeamKey(request.team_key) if request.team_key else Community.get_by_id(request.community_id)
        role = request.role if request.role else UserRoleType.MEMBER

        resp = None
        if user and community:
            circle = 0
            for circle_value, circle_name in community.circles.iteritems():
                if circle_name == request.circle:
                    circle = int(circle_value)

            resp = UserRole.insert(user, community, role, circle)
            send_added_user_email(community.name, user.display_name, "added", action_user.display_name, community.team_hash)

        return ResponseMessage(success=True if resp else False)
예제 #10
0
파일: utils.py 프로젝트: usersource/anno
def user_community(user):
    userroles = UserRole.query().filter(UserRole.user == user.key)\
                                .fetch(projection=[UserRole.community, UserRole.role, UserRole.circle_level])

    results = []
    for userrole in userroles:
        results.append(dict(community=userrole.community, role=userrole.role, circle_level=userrole.circle_level))

    return results
예제 #11
0
파일: utils.py 프로젝트: usersource/anno
def is_auth_user_admin(headers=None, action_auth_user=None):
    is_admin = False
    user = auth_user(headers) if (not action_auth_user and headers) else action_auth_user
    if user:
        community = Community.getCommunityFromTeamKey(user.account_type)
        if community:
            role = UserRole.getRole(user, community)
            is_admin = role == UserRoleType.ADMIN

    return is_admin
예제 #12
0
파일: utils.py 프로젝트: usersource/anno
def auth_user(headers):
    current_user = get_endpoints_current_user(raise_unauthorized=False)
    user = None

    if current_user is None:
        credential_pair = get_credential(headers)

        signinMethod = SignInMethod.ANNO
        team_key = None
        team_secret = None
        display_name = None
        image_url = None

        if len(credential_pair) == 2:
            email, password = credential_pair
        elif len(credential_pair) == 5:
            signinMethod, email, password, team_key, team_secret = credential_pair
        else:
            signinMethod, email, password, team_key, team_secret, display_name, image_url = credential_pair

        validate_email(email)
        user = User.find_user_by_email(email, team_key)

        if signinMethod == SignInMethod.ANNO:
            User.authenticate(email, md5(password))
        elif signinMethod == SignInMethod.PLUGIN:
            if not Community.authenticate(team_key, team_secret):
                 raise endpoints.UnauthorizedException("Incorrect team key or secret")

            display_name = unicode(display_name, "utf-8", "ignore")
            if not user:
                user = User.insert_user(email=email, username=display_name, account_type=team_key, image_url=image_url)
                community = Community.getCommunityFromTeamKey(team_key)
                UserRole.insert(user, community)
            elif (display_name and display_name != user.display_name) or (image_url and image_url != user.image_url):
                User.update_user(user=user, email=email, username=display_name, account_type=team_key, image_url=image_url)
    else:
        user = User.find_user_by_email(current_user.email())

    if user is None:
        raise endpoints.UnauthorizedException("Oops, something went wrong. Please try later.")

    return user
예제 #13
0
파일: anno.py 프로젝트: usersource/anno
    def insert_anno(cls, message, user):
        """
        create a new anno model from request message.
        """
        itemCount = 0
        appinfo, community = getAppAndCommunity(message, user)

        circle_level = 0
        if community:
            itemCount = cls.countItemsForTeam(community.key)
            circle_level = UserRole.getCircleLevel(user, community)
            if message.circle_level and (message.circle_level <= circle_level):
                circle_level = message.circle_level

        entity = cls(anno_text=message.anno_text, anno_type=message.anno_type,
                     level=message.level, device_model=message.device_model,
                     os_name=message.os_name, os_version=message.os_version,
                     creator=user.key, draw_elements=message.draw_elements,
                     image=message.image, screenshot_is_anonymized=message.screenshot_is_anonymized,
                     geo_position=message.geo_position, flag_count=0, vote_count=0,
                     followup_count=0, latitude=message.latitude, longitude=message.longitude,
                     screen_info=message.screen_info)

        # set appinfo and community
        entity.app = appinfo.key
        entity.community = community.key if community else None
        entity.circle_level = circle_level

        # set created time if provided in the message.
        if message.created is not None:
            entity.created = message.created

        # use google map api to retrieve country information and save into datastore.
        if message.latitude is not None and message.longitude is not None:
            entity.country = get_country_by_coordinate(message.latitude, message.longitude)

        # set last update time & activity
        entity.last_update_time = datetime.datetime.now()
        entity.last_activity = 'UserSource'
        entity.last_update_type = 'create'
        anno_key = entity.put()

        entity.anno_id = anno_key.id()
        entity.put()

        # update user anno state
        from model.userannostate import UserAnnoState
        UserAnnoState.insert(user=user, anno=entity, type=AnnoActionType.CREATED)

        if community:
            itemCount = cls.query_count_by_community(community_key=community.key)
            if itemCount == 0:
                send_first_anno_email(community.name, user.display_name)

        return entity
예제 #14
0
    def edit_user_role(self, request):
        user = get_user_from_request(user_id=request.user_id, user_email=request.user_email)
        community = Community.get_by_id(request.community_id)
        resp = None

        if community:
            if user:
                resp = UserRole.edit(user, community, request.role)
            elif request.include_invite:
                resp = Invite.change_user_role(request.user_email, community, request.role)

        return ResponseMessage(success=True if resp else False)
예제 #15
0
    def get_admin_master_data(self, request):
        communities_message = []
        query = Community.query().filter(Community.team_secret != None)

        if request.team_key:
            query = query.filter(Community.team_key == request.team_key)

        communities = query.fetch()

        for community in communities:
            community_message = CommunityAdminMasterMessage()
            community_message.community_name = community.name
            community_message.team_key = community.team_key
            community_message.team_secret = community.team_secret
            community_message.team_hash = community.team_hash
            community_message.plan = community.plan

            app = community.apps[0].get()
            if app:
                community_message.app_name = app.name
                community_message.app_icon = app.icon_url

            community_message.users = []
            if request.get_user_list:
                for userrole in UserRole.community_user_list(community_key=community.key):
                    user = userrole.user.get()
                    if user and (user.account_type == community.team_key):
                        if user.user_email.split("@")[1] == "devnull.usersource.io":
                            break

                        user_message = UserAdminMasterMessage()
                        user_message.display_name = user.display_name
                        user_message.user_email = user.user_email
                        user_message.password_present = True if user.password else False
                        user_message.role = userrole.role
                        user_message.image_url = user.image_url
                        if community.circles:
                            user_message.circle = community.circles.get(str(userrole.circle_level))
                        community_message.users.append(user_message)

            communities_message.append(community_message)

        return CommunityAdminMasterListMessage(communities=communities_message)
예제 #16
0
    def user_list(self, request):
        community_user_message_list = []

        status = InvitationStatusType.ACCEPTED
        userroles = UserRole.community_user_list(request.id)
        for userrole in userroles:
            user = userrole.user.get()
            if user:
                user_message = UserMessage(id=user.key.id(), display_name=user.display_name, user_email=user.user_email)
                community_user_message = CommunityUserMessage(user=user_message, role=userrole.role, status=status)
                community_user_message_list.append(community_user_message)

        if request.include_invite:
            status = InvitationStatusType.PENDING
            from model.invite import Invite
            invited_users = Invite.list_by_community(request.id)
            for invited_user in invited_users:
                user_message = UserMessage(display_name=invited_user.name, user_email=invited_user.email)
                community_user_message = CommunityUserMessage(user=user_message, role=invited_user.role, status=status)
                community_user_message_list.append(community_user_message)

        return CommunityUserListMessage(user_list=community_user_message_list)
예제 #17
0
    def get_noft_devices(cls, first_user, anno, action_type):
        """
        Get list of device ids to which notification to be sent

        :param ndb.Model first_user: "******" datastore of user who did anno action
        :param ndb.Model anno: "anno" datastore
        :param str action_type: one of the :py:class:`.AnnoActionType`
        :returns: list of device ids for iOS and Android devices
        :rtype: dict
        """
        interested_user_deviceids = {PlatformType.IOS: [], PlatformType.ANDROID: []}
        community_manager_deviceids = {PlatformType.IOS: [], PlatformType.ANDROID: []}

        # get all interested users for anno if action_type is other than "created"
        if action_type != AnnoActionType.CREATED:
            interested_user_list = UserAnnoState.list_users_by_anno(
                anno_key=anno.key, projection=[UserAnnoState.user, UserAnnoState.last_read]
            )
            interested_user_deviceids = cls.list_deviceid(interested_user_list)

        # anno is in community-scope then send notification to all managers of that community
        if anno.community:
            community_id = anno.community.id()
            community_manager_list = UserRole.community_user_list(community_id=community_id, only_managers=True)
            community_manager_deviceids = cls.list_deviceid(community_manager_list)

        # merging device ids of interested users and community managers
        notf_devices = {
            platform: list(set(interested_user_deviceids[platform] + community_manager_deviceids[platform]))
            for platform in interested_user_deviceids
        }

        # removing first user from push notification task
        if first_user.device_id and first_user.device_type:
            if first_user.device_id in notf_devices[first_user.device_type]:
                notf_devices[first_user.device_type].remove(first_user.device_id)

        return notf_devices
예제 #18
0
파일: invite.py 프로젝트: usersource/anno
    def accept(cls, message):
        resp = None
        msg = ""
        invitation = cls.query(cls.invite_hash == message.invite_hash).get()

        if invitation:
            community = invitation.community.get()
            if community:
                if (invitation.email == message.user_email) or message.force:
                    user = User.find_user_by_email(message.user_email)
                    resp = UserRole.insert(user, community, invitation.role)
                    if resp:
                        invitation.key.delete()
                        msg = "Invitation accepted"
                    else:
                        msg = "Error while adding user to community"
                else:
                    msg = "User Mismatch"
            else:
                msg = "Community no longer exist"
        else:
            msg = "Invitation no longer exist"

        return (resp, msg)
예제 #19
0
    def create_sdk_team(cls, message, pricing_plan=False, stripe_token=None):
        team_key = message.team_key
        app_name = message.app.name
        community_name = message.community_name or app_name
        plan = message.plan or PlanType.BASIC

        app = AppInfo.query().filter(AppInfo.lc_name == app_name.lower()).get()
        if not app:
            appinfo_message = AppInfoMessage()
            appinfo_message.name = app_name
            appinfo_message.icon_url = message.app.icon_url
            appinfo_message.version = message.app.version
            app = AppInfo.insert(appinfo_message)

        from helper.utils import md5
        community_message = CommunityMessage(name=community_name,
                                             team_key=team_key,
                                             team_secret=md5(community_name.lower()),
                                             plan=plan)
        community_message.user = UserMessage(user_email=message.admin_user.user_email,
                                             display_name=message.admin_user.display_name,
                                             password=message.admin_user.password)
        community, user = cls.insert(community_message, getCommunity=True)

        communities_message = []
        if community and app:
            if not app.key in community.apps:
                community.apps.append(app.key)
                community.put()

            # response message
            community_message = CommunityAdminMasterMessage()
            community_message.community_name = community.name
            community_message.team_key = community.team_key
            community_message.team_secret = community.team_secret
            # community_message.team_hash = community.team_hash
            community_message.app_name = app.name
            community_message.app_icon = app.icon_url

            community_message.users = []
            from model.userrole import UserRole

            user_message = UserAdminMasterMessage()
            user_message.display_name = user.display_name
            user_message.user_email = user.user_email
            user_message.password_present = True if user.password else False
            user_message.role = UserRole.getRole(user, community)
            user_message.image_url = user.image_url

            if community.circles:
                user_message.circle = community.circles.get(str(UserRole.getCircleLevel(user, community)))

            community_message.users.append(user_message)
            communities_message.append(community_message)
            registration_successful = True

            if pricing_plan:
                if stripe_token:
                    payment_success = StripePayment.create_charge(stripe_token, community.key, plan)
                    if not payment_success:
                        registration_successful = False
                else:
                    registration_successful = False

            if registration_successful:
                from helper.utils import send_created_team_email
                from helper.utils import send_access_team_email
                send_created_team_email(community.name, user.display_name)
                send_access_team_email(user.user_email, community.team_hash,
                                       community.name, community.team_key,
                                       community.team_secret)
            else:
                community.key.delete()
                communities_message = []

        return communities_message
예제 #20
0
    def insert(cls, message, getCommunity=False):
        community, user = None, None

        try:
            from helper.utils import get_user_from_request

            if message.name is None:
                return "Community name is required" if not getCommunity else (community, user)

            if message.type:
                # community should be of type 'private' or 'public'
                if not message.type in [CommunityType.PRIVATE, CommunityType.PUBLIC]:
                    return "Community should be of type 'private' or 'public'" if not getCommunity else (community, user)
                # only one public community is allowed
                elif message.type == CommunityType.PUBLIC:
                    queryResultCount = Community.query(Community.type == message.type).count()
                    if queryResultCount:
                        return "Community not created. Can't create more than one public community." if not getCommunity else (community, user)
            else:
                message.type = CommunityType.PRIVATE

            community = cls.getCommunityFromTeamKey(team_key=message.team_key)
            if not community:
                from helper.utils import md5
                team_hash = md5(message.team_key)[-8:]

                community = cls(name=message.name, description=message.description,
                                welcome_msg=message.welcome_msg, type=message.type,
                                team_key=message.team_key, team_secret=message.team_secret,
                                team_hash=team_hash, plan=message.plan)
                community.circles = { CircleValue.CONTRIBUTOR : CircleType.CONTRIBUTOR,
                                      CircleValue.BETA_TESTER : CircleType.BETA_TESTER,
                                      CircleValue.ALPHA_TESTER : CircleType.ALPHA_TESTER,
                                      CircleValue.DEVELOPER : CircleType.DEVELOPER }
                community.put()
                respData = "Community created."

            user = get_user_from_request(user_id=message.user.id,
                                         user_email=message.user.user_email,
                                         team_key=message.team_key)
            userrole = None
            userrole_type = UserRoleType.ADMIN if message.team_key else UserRoleType.MANAGER

            if (not user) and message.team_key and message.user.user_email:
                from model.user import User
                from helper.utils import md5
                user = User.insert_user(message.user.user_email,
                                        username=message.user.display_name,
                                        account_type=message.team_key,
                                        auth_source=AuthSourceType.PLUGIN,
                                        password=md5(message.user.password),
                                        image_url="")

            if user:
                from model.userrole import UserRole
                userrole = UserRole.insert(user, community, userrole_type, int(CircleValue.DEVELOPER))

            if userrole is None:
                community.key.delete()
                respData = "Community is not created as user doesn't exist"

        except Exception as e:
            logging.exception("Exception while inserting community: %s" % e)
            respData = e

        return respData if not getCommunity else (community, user)