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 > 3600 ] # 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, "")
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 HackathonPlayerType.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)
def __oauth_login_db(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) list( 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.") list( map(lambda x: self.__create_or_update_email(user, x), email_list)) # generate API token token = self.__generate_api_token(user) resp = {"token": token.dic(), "user": user.dic()} return resp
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()
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
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()
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
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
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
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()}
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=HackathonPlayerType.ADMIN).count() > 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)
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=HackathonPlayerType.COMPETITOR, deleted=False, status__in=[ HackathonPlayerStatus.AUTO_PASSED, HackathonPlayerStatus.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
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
def __get_existing_user(self, openid, provider): return User.objects(openid=openid, provider=provider).first()
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]