Пример #1
0
    def check_user_online_status(self):
        """Check whether the user is offline. If the answer is yes, update its status in DB."""
        overtime_user_ids = [user_id for user_id in users_operation_time
                             if (self.util.get_now() - users_operation_time[user_id]).seconds > 1800]  # 1800s-half hour

        User.objects(id__in=overtime_user_ids).update(online=False)
        for user_id in overtime_user_ids:
            users_operation_time.pop(user_id, "")
Пример #2
0
    def check_user_online_status(self):
        """Check whether the user is offline. If the answer is yes, update its status in DB."""
        overtime_user_ids = [user_id for user_id in users_operation_time
                             if (self.util.get_now() - users_operation_time[user_id]).minutes > 60]
        # 3600s- expire as token expire

        User.objects(id__in=overtime_user_ids).update(online=False)
        for user_id in overtime_user_ids:
            users_operation_time.pop(user_id, "")
Пример #3
0
    def get_user_fezzy_search(self, hackathon, args):
        """fezzy search user by name, nickname and email

        :type **kwargs: dict
        :param **kwargs: dict should has key['condition']

        :rtype: list
        :return a list of users or empty list if not user match conditions
        """

        keyword = args.get("keyword", "")
        page = int(args.get("page", 1))
        per_page = int(args.get("per_page", 20))

        pagination = User.objects(
            Q(name__icontains=keyword) | Q(nickname__icontains=keyword)
            | Q(emails__email__icontains=keyword)).paginate(page, per_page)

        def get_user_details(user):
            user_info = self.user_display_info(user)

            user_hackathon = UserHackathon.objects(hackathon=hackathon,
                                                   user=user).first()
            user_info[
                "role"] = user_hackathon.role if user_hackathon else HACK_USER_TYPE.VISITOR
            user_info[
                "remark"] = user_hackathon.remark if user_hackathon else ""

            return user_info

        # return serializable items as well as total count
        return self.util.paginate(pagination, get_user_details)
Пример #4
0
    def get_user_fezzy_search(self, hackathon, args):
        """fezzy search user by name, nickname and email

        :type **kwargs: dict
        :param **kwargs: dict should has key['condition']

        :rtype: list
        :return a list of users or empty list if not user match conditions
        """

        keyword = args.get("keyword", "")
        page = int(args.get("page", 1))
        per_page = int(args.get("per_page", 20))

        pagination = User.objects(
            Q(name__icontains=keyword) |
            Q(nickname__icontains=keyword) |
            Q(emails__email__icontains=keyword)).paginate(page, per_page)

        def get_user_details(user):
            user_info = self.user_display_info(user)

            user_hackathon = UserHackathon.objects(hackathon=hackathon, user=user).first()
            user_info["role"] = user_hackathon.role if user_hackathon else HACK_USER_TYPE.VISITOR
            user_info["remark"] = user_hackathon.remark if user_hackathon else ""

            return user_info

        # return serializable items as well as total count
        return self.util.paginate(pagination, get_user_details)
Пример #5
0
    def get_expr_list_by_hackathon_id(self, hackathon, context):
        # get a list of all experiments' detail
        user_name = context.user_name if "user_name" in context else None
        status = context.status if "status" in context else None
        page = int(context.page) if "page" in context else 1
        per_page = int(context.per_page) if "per_page" in context else 10
        users = User.objects(name=user_name).all() if user_name else []

        if user_name and status:
            experiments_pagi = Experiment.objects(hackathon=hackathon,
                                                  status=status,
                                                  user__in=users).paginate(
                                                      page, per_page)
        elif user_name and not status:
            experiments_pagi = Experiment.objects(hackathon=hackathon,
                                                  user__in=users).paginate(
                                                      page, per_page)
        elif not user_name and status:
            experiments_pagi = Experiment.objects(hackathon=hackathon,
                                                  status=status).paginate(
                                                      page, per_page)
        else:
            experiments_pagi = Experiment.objects(
                hackathon=hackathon).paginate(page, per_page)

        return self.util.paginate(experiments_pagi,
                                  self.__get_expr_with_detail)
Пример #6
0
    def __oauth_login(self, provider, context):
        # update db
        email_list = context.get("email_list", [])
        openid = context.openid

        user = self.__get_existing_user(openid, provider)
        if user is not None:
            user.update(
                provider=provider,
                name=context.get("name", user.name),
                nickname=context.get("nickname", user.nickname),
                access_token=context.get("access_token", user.access_token),
                avatar_url=context.get("avatar_url", user.avatar_url),
                last_login_time=self.util.get_now(),
                login_times=user.login_times + 1,
                online=True,
            )
            map(lambda x: self.__create_or_update_email(user, x), email_list)
        else:
            user = User(
                openid=openid,
                name=context.name,
                provider=provider,
                nickname=context.nickname,
                access_token=context.access_token,
                avatar_url=context.get("avatar_url", ""),
                login_times=1,
                online=True,
            )

            try:
                user.save()
            except ValidationError as e:
                self.log.error(e)
                return internal_server_error("create user fail.")

            map(lambda x: self.__create_or_update_email(user, x), email_list)

        # oxford only
        if provider == "alauda":
            self.__oxford(user, context.get("oxford_api"))

        # generate API token
        token = self.__generate_api_token(user)
        return {"token": token.dic(), "user": user.dic()}
Пример #7
0
    def __oauth_login(self, provider, context):
        # update db
        email_list = context.get('email_list', [])
        openid = context.openid

        user = self.__get_existing_user(openid, provider)
        if user is not None:
            user.update(
                provider=provider,
                name=context.get("name", user.name),
                nickname=context.get("nickname", user.nickname),
                access_token=context.get("access_token", user.access_token),
                avatar_url=context.get("avatar_url", user.avatar_url),
                last_login_time=self.util.get_now(),
                login_times=user.login_times + 1,
                online=True)
            map(lambda x: self.__create_or_update_email(user, x), email_list)
        else:
            user = User(openid=openid,
                        name=context.name,
                        provider=provider,
                        nickname=context.nickname,
                        access_token=context.access_token,
                        avatar_url=context.get("avatar_url", ""),
                        login_times=1,
                        online=True)

            try:
                user.save()
            except ValidationError as e:
                self.log.error(e)
                return internal_server_error("create user fail.")

            map(lambda x: self.__create_or_update_email(user, x), email_list)

        # oxford only
        if provider == "alauda":
            self.__oxford(user, context.get("oxford_api"))

        # generate API token
        token = self.__generate_api_token(user)
        return {
            "token": token.dic(),
            "user": user.dic()}
Пример #8
0
def setup_db():
    """Initialize db tables

    make sure database and user correctly created in db
    in case upgrade the table structure, the origin table need be dropped firstly
    """
    # init REQUIRED db data.

    # reserved user is deleted, may not need in mongodb implementation

    # default super admin

    admin = User(
        name="admin",
        nickname="admin",
        password="******",
        is_super=True)

    User.objects(name="admin").update_one(__raw__={"$set": admin.to_mongo().to_dict()}, upsert=True)
Пример #9
0
    def get_user_by_id(self, user_id):
        """Query user by unique id

        :type user_id: str
        :param user_id: _id of the user to query

        :rtype: User
        :return: instance of User or None if user not found
        """
        return User.objects(id=user_id).first()
Пример #10
0
    def get_user_by_id(self, user_id):
        """Query user by unique id

        :type user_id: str
        :param user_id: _id of the user to query

        :rtype: User
        :return: instance of User or None if user not found
        """
        return User.objects(id=user_id).first()
Пример #11
0
def setup_db():
    """Initialize db tables

    make sure database and user correctly created in db
    in case upgrade the table structure, the origin table need be dropped firstly
    """
    # init REQUIRED db data.

    # reserved user is deleted, may not need in mongodb implementation

    # default super admin

    admin = User(name="admin",
                 nickname="admin",
                 password="******",
                 avatar_url="/static/pic/monkey-32-32px.png",
                 is_super=True)

    User.objects(name="admin").update_one(
        __raw__={"$set": admin.to_mongo().to_dict()}, upsert=True)
Пример #12
0
def add_super_user(name, nickname, password, is_super=True):
    admin = User(
        name=name,
        nickname=nickname,
        avatar_url="/static/pic/monkey-32-32px.png",
        is_super=is_super)
    admin.set_password(password)

    User.objects(name=name).update_one(__raw__={"$set": admin.to_mongo().to_dict()}, upsert=True)
    return admin
Пример #13
0
    def get_user_by_email(self, email):
        """Query user by email

        :type email: str|unicode
        :param email: email address

        :rtype: User
        :return instance of User or None if user cannot be found
        """
        if email is None:
            return None

        return User.objects(emails__email=email).first()
Пример #14
0
    def get_user_by_email(self, email):
        """Query user by email

        :type email: str|unicode
        :param email: email address

        :rtype: User
        :return instance of User or None if user cannot be found
        """
        if email is None:
            return None

        return User.objects(emails__email=email).first()
Пример #15
0
    def __db_login(self, context):
        username = context.get("username")
        enc_pwd = context.get("password")

        user = User.objects(name=username, password=enc_pwd).first()
        if user is None:
            self.log.warn("invalid user/pwd login: username=%s, encoded pwd=%s" % (username, enc_pwd))
            return None

        user.online = True
        user.login_times = (user.login_times or 0) + 1
        user.save()

        token = self.__generate_api_token(user)
        return {"token": token.dic(), "user": user.dic()}
Пример #16
0
def user2():
    # return new user named two
    two = User(
        name="test_two",
        nickname="test_two",
        avatar_url="/static/pic/monkey-32-32px.png",
        is_super=False)
    two.set_password("test_password")
    two.save()
    return two
Пример #17
0
def user1():
    # return new user named one
    one = User(
        name="test_one",
        nickname="test_one",
        avatar_url="/static/pic/monkey-32-32px.png",
        is_super=False)
    one.set_password("test_password")
    one.save()
    return one
Пример #18
0
def admin1():
    # return new admin named one
    admin_one = User(
        name="admin_one",
        nickname="admin_one",
        avatar_url="/static/pic/monkey-32-32px.png",
        is_super=True)
    admin_one.set_password("test_password")
    admin_one.save()
    return admin_one
Пример #19
0
    def __db_login(self, context):
        username = context.get("username")
        enc_pwd = context.get("password")

        user = User.objects(name=username, password=enc_pwd).first()
        if user is None:
            self.log.warn(
                "invalid user/pwd login: username=%s, encoded pwd=%s" %
                (username, enc_pwd))
            return unauthorized("username or password error")

        user.online = True
        user.login_times = (user.login_times or 0) + 1
        user.save()

        token = self.__generate_api_token(user)
        return {"token": token.dic(), "user": user.dic()}
Пример #20
0
    def is_hackathon_admin(self, hackathon_id, user_id):
        """Check whether user is admin of specific hackathon

        :type hackathon_id: string or object_id
        :param hackathon_id: id of hackathon

        :type user_id: string or object_id
        :param user_id: the id of user to be checked

        :rtype: bool
        :return True if specific user has admin privilidge on specific hackathon otherwise False
        """
        if User.objects(id=user_id, is_super=True).count():
            return True

        return UserHackathon.objects(user=user_id,
                                     hackathon=hackathon_id,
                                     role=HACK_USER_TYPE.ADMIN).count() > 0
Пример #21
0
    def get_expr_list_by_hackathon_id(self, hackathon, context):
        # get a list of all experiments' detail
        user_name = context.user_name if "user_name" in context else None
        status = context.status if "status" in context else None
        page = int(context.page) if "page" in context else 1
        per_page = int(context.per_page) if "per_page" in context else 10
        users = User.objects(name=user_name).all() if user_name else []

        if user_name and status:
            experiments_pagi = Experiment.objects(hackathon=hackathon, status=status, user__in=users).paginate(page, per_page)
        elif user_name and not status:
            experiments_pagi = Experiment.objects(hackathon=hackathon, user__in=users).paginate(page, per_page)
        elif not user_name and status:
            experiments_pagi = Experiment.objects(hackathon=hackathon, status=status).paginate(page, per_page)
        else:
            experiments_pagi = Experiment.objects(hackathon=hackathon).paginate(page, per_page)

        return self.util.paginate(experiments_pagi, self.__get_expr_with_detail)
Пример #22
0
    def is_hackathon_admin(self, hackathon_id, user_id):
        """Check whether user is admin of specific hackathon

        :type hackathon_id: string or object_id
        :param hackathon_id: id of hackathon

        :type user_id: string or object_id
        :param user_id: the id of user to be checked

        :rtype: bool
        :return True if specific user has admin privilidge on specific hackathon otherwise False
        """
        if User.objects(id=user_id, is_super=True).count():
            return True

        return UserHackathon.objects(
            user=user_id,
            hackathon=hackathon_id,
            role=HACK_USER_TYPE.ADMIN).count() > 0
Пример #23
0
    def __get_hackathon_stat(self, hackathon):
        stats = HackathonStat.objects(hackathon=hackathon).all()
        result = {"hackathon_id": str(hackathon.id), "online": 0, "offline": 0}
        for item in stats:
            result[item.type] = item.count

        reg_list = UserHackathon.objects(
            hackathon=hackathon,
            role=HACK_USER_TYPE.COMPETITOR,
            deleted=False,
            status__in=[
                HACK_USER_STATUS.AUTO_PASSED, HACK_USER_STATUS.AUDIT_PASSED
            ]).only("user").no_dereference().all()
        reg_list = [uh.user.id for uh in reg_list]
        reg_count = len(reg_list)
        if reg_count > 0:
            online_count = User.objects(id__in=reg_list, online=True).count()
            result["online"] = online_count
            result["offline"] = reg_count - online_count

        return result
Пример #24
0
    def __get_hackathon_stat(self, hackathon):
        stats = HackathonStat.objects(hackathon=hackathon).all()
        result = {
            "hackathon_id": str(hackathon.id),
            "online": 0,
            "offline": 0
        }
        for item in stats:
            result[item.type] = item.count

        reg_list = UserHackathon.objects(hackathon=hackathon,
                                         role=HACK_USER_TYPE.COMPETITOR,
                                         deleted=False,
                                         status__in=[HACK_USER_STATUS.AUTO_PASSED, HACK_USER_STATUS.AUDIT_PASSED]
                                         ).only("user").no_dereference().all()
        reg_list = [uh.user.id for uh in reg_list]
        reg_count = len(reg_list)
        if reg_count > 0:
            online_count = User.objects(id__in=reg_list, online=True).count()
            result["online"] = online_count
            result["offline"] = reg_count - online_count

        return result
Пример #25
0
 def __get_existing_user(self, openid, provider):
     return User.objects(openid=openid, provider=provider).first()
Пример #26
0
    def get_talents(self):
        # todo real talents list
        users = User.objects(name__ne="admin").order_by("-login_times")[:10]

        return [self.user_display_info(u) for u in users]
Пример #27
0
    def authing(self, context):
        token = context.token
        username = context.username

        if not token or not username:
            self.log.info(
                "Unable to handle authing login request. Either token or username is empty. username: "******"Unable to handle authing login request. Either token or username is empty"
            )

        # validate access token
        self.log.info("Validate authing token for user %s" % username)
        validate_url = get_config("login.authing.validate_token_url") + token
        validate_raw_resp = get_remote(validate_url)
        validate_resp = json.loads(validate_raw_resp)

        if int(validate_resp["code"]) != 200 or not bool(
                validate_resp["status"]):
            self.log.info("Token invalid: %s" % validate_raw_resp)
            return unauthorized("Token invalid: %s" % validate_raw_resp)

        authing_id = context._id
        open_id = context.unionid
        provider = context.registerMethod
        if "oauth" in provider:
            # OAuth like github. registerMethod example: "oauth:github"
            provider = provider[6:]
        else:
            # Authing user: using authing_id as open_id
            open_id = authing_id

        email_list = [{
            "email": context.get("email", ""),
            "primary": True,
            "verified": bool(context.get("emailVerified", False))
        }]

        user = self.__get_existing_user(open_id, provider)
        if user is not None:
            nickname = context.get("nickname", user.nickname)
            if not nickname:
                nickname = user.name
            user.update(name=context.get("username", user.name),
                        nickname=nickname,
                        access_token=context.get("token", user.access_token),
                        avatar_url=context.get("photo", user.avatar_url),
                        authing_id=authing_id,
                        last_login_time=self.util.get_now(),
                        login_times=user.login_times + 1,
                        online=True)
            list(
                map(lambda x: self.__create_or_update_email(user, x),
                    email_list))
        else:
            user = User(openid=open_id,
                        name=username,
                        provider=provider,
                        authing_id=authing_id,
                        nickname=context.nickname,
                        access_token=token,
                        avatar_url=context.get("photo", ""),
                        login_times=int(context.get("loginsCount", "1")),
                        online=True)

            try:
                user.save()
            except ValidationError as e:
                self.log.error(e)
                return internal_server_error("create user fail.")

            list(
                map(lambda x: self.__create_or_update_email(user, x),
                    email_list))

        # save API token
        token_expire_date = self.util.get_now() + timedelta(hours=1)
        if "tokenExpiredAt" in context:
            try:
                token_expire_date = datetime.strptime(
                    context.tokenExpiredAt, '%a %b %d %Y %H:%M:%S GMT%z (CST)')
            except Exception as e:
                self.log.warn(
                    "Unable to parse tokenExpiredAt: %s. Will use 1 hour as expiry."
                    % context.tokenExpiredAt)
        else:
            self.log.info(
                "tokenExpiredAt not included in authing response. Will use 1 hour as expiry."
            )

        user_token = UserToken(token=token,
                               user=user,
                               expire_date=token_expire_date)
        user_token.save()
        # resp = {
        #     "token": user_token.dic(),
        #     "user": user.dic()
        # }
        resp = context.to_dict()
        resp.update(user.dic())
        return resp
Пример #28
0
    def get_talents(self):
        # todo real talents list
        users = User.objects(name__ne="admin").order_by("-login_times")[:10]

        return [self.user_display_info(u) for u in users]
Пример #29
0
 def get_talents(self):
     # todo real talents list
     users = User.objects(name__ne="admin").order_by("-login_times")[:10]
     # fixme why delete this log will panic
     self.log.debug("get talents {}".format(users))
     return [self.user_display_info(u) for u in users]
Пример #30
0
 def __get_existing_user(self, openid, provider):
     return User.objects(openid=openid, provider=provider).first()