Пример #1
0
    def get(self):
        """
        获取用户列表
        """

        keyword = self.get_argument("kw", "")
        sort = intval(self.get_argument("sort", 0))

        query = User.select()

        if keyword:
            query = query.where((User.name.contains(keyword))
                                | (User.mobile == keyword))

        if sort == 2:
            query = query.order_by(User.name.desc())
        else:
            query = query.order_by(User.id.desc())

        users = self.paginate_query(query)

        self.render(
            "user/list.html",
            users=users,
        )
Пример #2
0
    def get_members(self, limit=20, offset=0, role="", state=None):
        """ 获取俱乐部成员
        """

        q = User.select(
            User, TeamMember
        ).join(
            TeamMember, on=TeamMember.user
        ).where(
            TeamMember.team == self
        )

        if role == "leader":
            q = q.where(TeamMember.role >= self.TeamRole.leader)

        elif role == "admin":
            q = q.where(TeamMember.role >= self.TeamRole.admin)

        if isinstance(state, int):
            q = q.where(TeamMember.state >= state)

        q = q.order_by(
            TeamMember.role.desc()
        ).offset(offset).limit(limit)

        users = []
        for user in q:
            users.append(user)

        return users
Пример #3
0
    def get(self, user_id):
        try:
            user = User.select(User, TeamMember).join(
                TeamMember,
                on=(TeamMember.user == User.id).alias("member")).where(
                    TeamMember.team == self.current_team,
                    TeamMember.user == user_id).get()
        except User.DoesNotExist:
            raise Http404()

        self.render("member/detail.html",
                    user=user,
                    groups=self.current_team.groups)
Пример #4
0
    def get(self, order_no):
        # order = TeamOrder.get_or_404(user=self.current_user,
        #                              order_no=order_no)
        try:
            order = TeamOrder.select(TeamOrder, Activity)\
                .join(Activity, on=(TeamOrder.activity_id == Activity.id)
                      .alias("activity"))\
                .where(TeamOrder.user == self.current_user,
                       TeamOrder.order_no == order_no)
            user = User.select().where(User.id == self.current_user.id)
            team = Team.select()
            order_pf = prefetch(order, user, team).get()
        except TeamOrder.DoesNotExist:
            raise ApiException(404, "订单不存在")

        self.write(SecureOrderSerializer(instance=order_pf).data)
Пример #5
0
    def validate_mobile(self, form):
        mobile = self.get_argument("mobile")
        verify_code = self.get_argument("verify_code")

        if not self.verify_mobile(mobile, verify_code):
            form.verify_code.errors = [ValidationError("验证码不正确")]
            return False

        if User.select().where(
            (User.mobile == mobile
             ) & (User.id != self.current_user.id)
        ).exists():
            form.mobile.errors = [ValidationError("手机号已存在")]
            return False

        return True
Пример #6
0
    def get_members(self, state=None):
        """ 获取活动成员列表

            Args:
                state: 指定状态

            Returns:
                Query
        """

        q = User.select(User, ActivityMember).join(
            ActivityMember,
            on=ActivityMember.user).where(ActivityMember.activity == self)

        if state is not None:
            q = q.where(ActivityMember.state == state)

        q = q.order_by(ActivityMember.nickname.asc(), User.name.asc())

        return q
Пример #7
0
    def validate_mobile(self, field):
        if not is_mobile(field.data):
            raise ValidationError('手机号码格式不正确')

        if User.select().where(User.mobile == field.data).exists():
            raise ValidationError('手机号码已存在')
Пример #8
0
    def post(self):

        mobile = self.get_argument("mobile")
        action = self.get_argument("action")

        if not is_mobile(mobile):
            raise ArgumentError(400, "手机号码格式不正确")

        sent_times_key = "yiyun:mobile:%s:code_sent_times" % mobile
        if intval(self.redis.get(sent_times_key)) >= 5:
            raise ArgumentError(400, "你已重发5次,请稍后再试")

        # 有效期内发送相同的验证码
        verify_code = random.randint(1000, 9999)
        is_registered = User.select().where(User.mobile == mobile).exists()
        self.logger.debug("send: %s to %s" % (verify_code, mobile))

        if action == "register" and is_registered:
            raise ArgumentError(1020, "手机号码已注册", status_code=400)

        if action in ('register_or_login', 'register', 'login'):
            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            tasks.message.send_sms_verifycode(mobile, verify_code)

            self.write_success(is_registered=is_registered)

        elif action == "forgot":

            if not is_registered:
                raise ArgumentError(400, "手机号码没有注册")

            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            tasks.message.send_sms_verifycode(mobile, verify_code)

            self.write_success()

        elif action == "update_mobile":
            if not self.current_user:
                raise ArgumentError(403, "登录后才能修改手机号")

            if is_registered:
                raise ArgumentError(403, "该号码已经使用,请更换")

            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            tasks.message.send_sms_verifycode(mobile, verify_code)

            # 关联验证码与当前用户
            self.redis.set(
                "ihealth:update_mobile:%s:verify_code:%s" %
                (mobile, verify_code), self.current_user.id)

            # 30分钟内有效
            self.redis.expire(
                "ihealth:update_mobile:%s:verify_code:%s" %
                (mobile, verify_code), 1800)

            self.write_success()

        # 30分钟内最多发送5次验证码
        sent_times = int(self.redis.incr(sent_times_key))
        if sent_times == 1:
            self.redis.expire(sent_times_key, 1800)
Пример #9
0
    def register_or_login(self, service, openid, access_token, expires_in,
                          nickname, gender, head_url, auth_data):

        try:
            user = User.select().join(
                UserAuthData,
                on=(UserAuthData.user_id == User.id
                    )).where((UserAuthData.service == service)
                             & (UserAuthData.openid == openid)).get()

        except User.DoesNotExist:
            user = None

        if self.current_user:

            # 已绑定到其它账号
            if user and user.id != self.current_user.id:
                raise ApiException(
                    403,
                    "此%s账号已被其他用户使用" % UserAuthData.get_service_name(service))

            # 已绑定到自己账号
            elif user and user.id == self.current_user.id:
                UserAuthData.update(
                    access_token=access_token,
                    expires_in=expires_in,
                    userinfo=auth_data).where(
                        (UserAuthData.service == service)
                        & (UserAuthData.user_id == user.id)).execute()

            # 已绑定其它账号
            elif UserAuthData.select().where(
                (UserAuthData.service == service)
                    & (UserAuthData.user_id == self.current_user.id)
                    & (UserAuthData.openid != openid)).exists():

                raise ApiException(
                    403, "你已绑定其他%s账号" % UserAuthData.get_service_name(service))

            # 已登录执行绑定
            else:
                UserAuthData.create(service=service,
                                    user_id=self.current_user.id,
                                    openid=openid,
                                    nickname=nickname,
                                    access_token=access_token,
                                    expires_in=expires_in,
                                    userinfo=auth_data)

                if self.device_id > 0:
                    User.update(last_device_id=self.device_id).where(
                        User.id == self.current_user.id).execute()

            self.write(self.create_session(self.current_user))

        else:
            # 已注册用户直接登录
            if user:
                update = {"last_login": datetime.now()}

                if self.device_id > 0:
                    update["last_device_id"] = self.device_id

                User.update(**update).where(User.id == user.id).execute()

                UserAuthData.update(
                    access_token=access_token,
                    expires_in=expires_in,
                    userinfo=auth_data).where(
                        (UserAuthData.service == service)
                        & (UserAuthData.user_id == user.id)).execute()

            # 未注册用户先注册
            else:

                with self.db.transaction() as txn:
                    if User.select().where(User.name == nickname).exists():
                        if nickname == "qzuser":
                            name = "%s_%s" % (nickname,
                                              random.randint(100000, 999999))
                        else:
                            name = "%s_%s" % (nickname, random.randint(
                                100, 999))

                    else:
                        name = nickname

                    user = User.create(
                        name=name,
                        gender=gender,
                        mobile_verifyed=False,
                        password=None,
                        reg_device_id=self.device_id,
                        last_device_id=self.device_id,
                        last_login=datetime.now(),
                        im_username=create_token(32).lower(),
                        im_password=create_token(16),
                    )

                    UserAuthData.create(service=service,
                                        user_id=user.id,
                                        openid=openid,
                                        nickname=nickname,
                                        access_token=access_token,
                                        expires_in=expires_in,
                                        userinfo=auth_data)

                    # 将手机好加到 redis, 匹配好友需要
                    if user.mobile:
                        self.redis.sadd('mobile:registered', user.mobile)

                    # 从第三方下载头像
                    if head_url:
                        tasks.user.update_avatar_by_url.delay(
                            user.id, head_url)

            if user and self.device_id:
                Device.update(owner_id=user.id).where(
                    Device.id == self.device_id).execute()

            self.write(self.create_session(user))
Пример #10
0
    def post(self):

        mobile = self.validated_arguments['mobile']
        action = self.validated_arguments['action']

        sent_times_key = "yiyun:mobile:%s:code_sent_times" % mobile
        if intval(self.redis.get(sent_times_key)) >= 5:
            raise ApiException(400, "你已重发5次,请稍后再试")

        # 有效期内发送相同的验证码
        verify_code = random.randint(1000, 9999)
        logging.debug('verify code for mobile[{0}]: {1}'.format(
            mobile, verify_code))
        is_registered = User.select().where(User.mobile == mobile).exists()

        if action == "register" and is_registered:
            raise ApiException(1020, "手机号码已注册", status_code=400)

        if action in ('register_or_login', 'register', 'login'):
            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            if not self.settings["debug"]:
                tasks.message.send_sms_verifycode(mobile, verify_code)

            self.write_success(is_registered=is_registered)

        elif action == "forgot":

            if not is_registered:
                raise ApiException(400, "手机号码没有注册")

            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            tasks.message.send_sms_verifycode(mobile, verify_code)

            self.write_success()

        elif action == "update_mobile":

            if not self.current_user:
                raise ApiException(403, "登录后才能修改手机号")

            if is_registered:
                raise ApiException(403, "该号码已经使用,请更换")

            if self.current_user.password and \
                    not User.check_password(self.current_user.password,
                                            self.validated_arguments["password"]):
                raise ApiException(403, "密码不正确,不能修改手机号")

            # 保存验证码
            self.save_verify_code(mobile, verify_code)

            # 发短信
            tasks.message.send_sms_verifycode(mobile, verify_code)

            # 关联验证码与当前用户
            self.redis.set(
                "yiyun:update_mobile:%s:verify_code:%s" %
                (mobile, verify_code), self.current_user.id)

            # 30分钟内有效
            self.redis.expire(
                "yiyun:update_mobile:%s:verify_code:%s" %
                (mobile, verify_code), 1800)

            self.write_success()

        # 30分钟内最多发送5次验证码
        sent_times = intval(self.redis.incr(sent_times_key))
        if sent_times == 1:
            self.redis.expire(sent_times_key, 1800)