Пример #1
0
def user_register(request):

    if request.method == 'POST':
        form = RegisterForm(request=request, data=request.POST)
        params = request.POST.get('params')
        if form.is_valid():
            user = form.register()
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            # password = form.cleaned_data['password']
            # 正式处理发送邮件
            # 加密用户的身份信息,生成激活token
            serializer = TJSS(settings.SECRET_KEY, 900)
            info = {'confirm': user.id}
            token = serializer.dumps(info)
            # 默认解码为utf8
            token = token.decode()
            # 使用celery发邮件
            send_activate_email.delay(email, username, token)
            rest = {'data': '注册成功!邮件正在发送,请前往邮箱激活账号'}
            return JsonResponse(rest)
        else:
            if params in ['password', 'repassword']:
                error = form.non_field_errors()
            else:
                error = form.errors.get(params)
            rest = {'data': error}
            return JsonResponse(rest)
    form = RegisterForm(request)
    return render(request, 'login/register.html', {'form': form})
Пример #2
0
    def post(self, request):
        """业务处理"""

        # 接收数据
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        phone = request.POST.get('phone')
        email = request.POST.get('email')

        # 校验数据
        if not all([username, password, phone, email]):
            # 缺少相关数据
            return HttpResponse('校验数据失败')

        user = User.objects.create_user(username, email, password, phone=phone)

        # 正式处理发送邮件
        # 加密用户的身份信息,生成激活token
        serializer = TJSS(settings.SECRET_KEY, 900)
        info = {'confirm': user.id}
        token = serializer.dumps(info)
        # 默认解码为utf8
        token = token.decode()

        # 使用celery发邮件
        send_activate_email.delay(email, username, token)

        return HttpResponse('注册成功,请注意查收激活账户邮件')
Пример #3
0
    def get(self, request):
        code = request.query_params.get("code")
        oauth = OAuthQQ()
        many_info = oauth.GetAccessToken(code=code)
        print("many_info>>>>>>>>>>>>>:", many_info)
        access_token = many_info.get("access_token")[0]
        expires_in = many_info.get("expires_in")[0]
        refresh_token = many_info.get("refresh_token")[0]

        if many_info.get("msg"):
            logging.error("code:{}, msg:{}".format(many_info.get("code"),
                                                   many_info.get("msg")))
            return Response("获取access_token失败",
                            status=status.HTTP_400_BAD_REQUEST)
        # 获取openid
        openid_info = oauth.GetOpenID(access_token=access_token)
        openid_dict = json.loads(openid_info)
        openid = openid_dict.get("openid")
        print('openid', type(openid))
        user_info = oauth.GetUserInfo(access_token=access_token, openid=openid)
        print(user_info)
        try:
            qq_user = OAuthUser.objects.get(openid=openid)
            user = qq_user.user
            # 生成jwt登录token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            try:
                avatar = user.avatar.url
            except:
                avatar = user_info.get("figureurl_qq_1")

            user_info = {
                "token": token,
                "id": user.id,
                "username": user.username,
                "avatar": avatar,
                "nickname": user_info.get("nickname"),
            }
            return Response({"user_info": user_info, "status": 1})
        except:
            # 没有进行QQ第三方关联
            serializer = TJSS(settings.SECRET_KEY,
                              constants.DATA_SIGNATURE_EXPIRE)
            data = serializer.dumps({
                'openid': openid,
                "access_token": access_token,
                "expires_in": expires_in,
                "refresh_token": refresh_token
            }).decode()
            return Response({
                "status": 0,
                "avatar": user_info.get("figureurl_qq_1"),
                "nickname": user_info.get("nickname"),
                "data": data
            })
Пример #4
0
    def post(self, request):
        """进行注册处理"""
        print("register post handle")
        # 接收数据
        username = request.POST.get('username')
        print("username: "******"password: "******"cpassword: "******"phone: ", phone)
        email = request.POST.get('email')
        print("email: ", email)
        allow = request.POST.get('allow')
        print("allow: ", allow)

        # 数据校验
        if not all([username, password, cpassword, email, phone, allow]):
            # 数据不完整
            return HttpResponse("用户数据不完整")
        # 校验邮箱
        # if not re.match():
        #     return render(request, 'register.html', {'errmsg': '邮箱格式不正确'})
        if allow != 'on':
            return HttpResponse("请同意注册协议")

        # 进行业务处理
        try:
            user = User.objects.get(username=username)
            user_admin = User.objects.get(is_admin=True)
        except User.DoesNotExist:
            user = None
            user_admin = None

        if user is None:
            user = User.objects.create_user(username, email, password)
            user.phone = phone
            user.is_active = 0
            if user_admin is None:
                user.is_admin = True
            user.save()

            ss = TJSS(settings.SECRET_KEY, 3600)
            info = {"id": user.id}
            token = ss.dumps(info).decode()
            tasks.send_register_active_email.delay(email, username, token)
        else:
            print("用户已存在, 注册失败")
            if user.is_active == 0:
                return HttpResponse('用户名已存在, 但未激活')
            else:
                return HttpResponse('用户名已存在, 注册失败')

        # 返回结果应答
        return HttpResponse("等待激活")
Пример #5
0
def generate_save_user_token(openid):
    """
    生成保存用户数据的token
    :param openid: 用户的openid
    :return: token
    """
    serializer = TJSS(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    data = {'openid': openid}
    token = serializer.dumps(data)
    return token.decode()
Пример #6
0
 def get(self, request, token):
     ss = TJSS(settings.SECRET_KEY, 3600)  # 3600s
     try:
         res = ss.loads(token)
         user = User.objects.get(id=res['id'])
         user.is_active = 1
         user.save()
         return HttpResponse("ok")
     except SignatureExpired:
         return HttpResponse("激活超时")
Пример #7
0
 def generate_verify_email_url(user_id, email):
     """
     生成验证邮箱的url
     """
     serializer = TJSS(settings.SECRET_KEY,
                       expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
     data = {'user_id': user_id, 'email': email}
     token = serializer.dumps(data).decode()
     verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
     return verify_url
Пример #8
0
def check_save_user_token(access_token):
    """
    检验保存用户数据的token
    :param token: token
    :return: openid or None
    """
    serializer = TJSS(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')
Пример #9
0
def password_reset(request, secret_username):
    serializer = TJSS(settings.SECRET_KEY, 900)
    info = serializer.loads(secret_username)
    username = info['username']
    print(username)
    user = User.objects.get(username=username)
    random_list = [chr(i) for i in list(range(65, 91)) + list(range(97, 123))
                   ] + [str(j) for j in range(10)]
    new_password = ''.join(random.sample(random_list, 9))
    print(new_password)
    user.set_password(new_password)
    send_password_reset_email(user.email, username, new_password)
    user.save()
    return render(request, 'forget_back.html')
Пример #10
0
def forget_password(request):
    form = ForgetPasswordForm()
    if request.method == 'POST':
        form = ForgetPasswordForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            user = User.objects.get(username=username)
            to_email = user.email
            serializer = TJSS(settings.SECRET_KEY, 900)
            info = {'username': username}
            secret_username = serializer.dumps(info)
            secret_username = secret_username.decode()
            send_forget_password_email(to_email, username, secret_username)
            return redirect('accounts:user_login')
    return render(request, 'forget.html', {'form': form})
Пример #11
0
 def check_verify_email_token(token):
     """
     检查验证邮件的token
     """
     serializer = TJSS(settings.SECRET_KEY,
                       expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
     try:
         data = serializer.loads(token)
     except BadData:
         return None
     else:
         email = data.get('email')
         user_id = data.get('user_id')
         try:
             user = User.objects.get(id=user_id, email=email)
         except User.DoesNotExist:
             return None
         else:
             return user
Пример #12
0
    def get(self, request, token):
        """点击邮件链接激活业务处理"""

        serializer = TJSS(settings.SECRET_KEY, 900)
        try:
            info = serializer.loads(token)

            # 获取要激活用户的id
            user_id = info['confirm']

            # 根据id获取用户信息
            user = User.objects.get(id=user_id)
            user.is_active = True
            user.save()
            # 跳转到登录页面
            return HttpResponseRedirect('/accounts/user/login/')

        except SignatureExpired as e:
            # 激活链接已过期,应重发激活邮件
            return HttpResponse('激活链接已过期!')
Пример #13
0
    def get(self, request, token):
        """点击邮件链接激活业务处理"""

        serializer = TJSS(settings.SECRET_KEY, 900)
        try:
            info = serializer.loads(token)

            # 获取要激活用户的id
            user_id = info['confirm']

            # 根据id获取用户信息
            user = User.objects.get(id=user_id)
            user.is_active = 1
            user.save()

            # 跳转到登录页面
            return redirect(reverse('user:login'))

        except SignatureExpired as se:
            # 激活链接已过期,应重发激活邮件
            return HttpResponse('激活链接已过期,请注意查收新的激活邮件!')
Пример #14
0
    def get(self, request):
        # 1. 获取前端传来的code值
        code = request.query_params.get('code', None)
        # 2. 判断前端是否传来了code值
        if not code:
            return Response({'error': '缺失code值'}, status=400)
        # 3. 通过code值获取access_token
        state = '/'
        qq = OAuthQQ(client_secret=settings.QQ_CLIENT_SECRET,
                     client_id=settings.QQ_CLIENT_ID,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)
        access_token = qq.get_access_token(code)
        # 4. 通过access_token获取openid
        openid = qq.get_open_id(access_token)
        # 5. 判断openid是否绑定多个用户
        try:
            qq_user = OAuthUser.objects.get('openid')
        except:
            tjss = TJSS(settings.SECRET_KEY, 300)
            openid = tjss.dumps({'openid': openid}).decode()

            # 6. 未绑定 跳转到绑定页面
            return Response({'access_token': openid})
        else:
            # 7. 绑定过, 则生成jwt_token
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                "token": token,
                "username": user.username,
                "user_id": user.id,
            })
Пример #15
0
    def validate(self, attrs):
        # 验证access_token
        # 解密
        tjss = TJSS(settings.SECRET_KEY, 300)
        try:
            data = tjss.loads(attrs['access_token'])
        except:
            raise serializers.ValidationError('access_token无效')

        # 获取openid
        openid = data.get('openid')
        # attrs添加属性
        attrs['openid'] = openid
        # 验证短信验证码
        # 1. 获取redis中真实短信
        conn = get_redis_connection('smscodes')
        rel_sms_code = conn.get('smscode_%s' % attrs['mobile'])
        # 2. 判断redis中短信是否有效
        if not rel_sms_code:
            raise serializers.ValidationError('短信验证码失效')
        # 3. 比对用户输入的短信和redis中真实短信
        if attrs['sms_code'] != rel_sms_code.decode():
            raise serializers.ValidationError('短信验证不一致')

        # 判断手机号是否注册过
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
            # 未注册 就注册为新用户
            return attrs
        else:
            # 注册过,就检查用户进行绑定
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
            print(attrs)
            return attrs
Пример #16
0
    def post(self, request):
        d = request.data.get("status")
        try:
            openid = request.data.get("data")

            serializer = TJSS(settings.SECRET_KEY,
                              constants.DATA_SIGNATURE_EXPIRE)
            data = serializer.loads(openid)
            open_id = data.get("openid")
            access_token = data.get("access_token")
            expires_in = data.get("expires_in")
            refresh_token = data.get("refresh_token")

        except:
            return Response("账号绑定超时,请重新登录绑定!",
                            status=status.HTTP_400_BAD_REQUEST)

        # 判断状态码
        if d != 1 and d != 2:
            return Response("QQ登录关联失败!", status=status.HTTP_400_BAD_REQUEST)
        nickname = request.data.get("nickname")
        if d == 1:
            username = request.data.get("count")
            password = request.data.get("password")
            user_avatar = request.data.get("avatar")

            try:
                checkuser = UsernameMobileAuthBackend()
                user = checkuser.authenticate(request,
                                              username=username,
                                              password=password)
                print(user)
            except:
                return Response("用户不存在!", status=status.HTTP_400_BAD_REQUEST)

            try:
                OAuthUser.objects.create(user_id=user.id,
                                         openid=open_id,
                                         access_token=access_token,
                                         expires_in=expires_in,
                                         refresh_token=refresh_token)
            except:
                return Response("QQ关联用户失败!",
                                status=status.HTTP_400_BAD_REQUEST)

        if d == 2:
            sms_code = request.data.get("sms_code")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            user_avatar = request.data.get("avatar")
            try:
                OAuthUser.objects.get(openid=open_id)
                return Response("QQ用户已经绑定另一个用户",
                                status=status.HTTP_400_BAD_REQUEST)
            except:
                pass

            try:
                User.objects.get(mobile=mobile)
                return Response("手机号码已被注册,请重新输入",
                                status=status.HTTP_400_BAD_REQUEST)
            except:
                pass

            try:
                redis_conn = get_redis_connection("sms_code")
                redis_sms_code = redis_conn.get("sms_%s" % mobile).decode()
                if redis_sms_code != sms_code:
                    return Response("验证码错误",
                                    status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response('redis数据库连接失败',
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            try:
                user = User.objects.create_user(username=mobile,
                                                mobile=mobile,
                                                password=password)
            except:
                return Response("创建用户失败", status=status.HTTP_400_BAD_REQUEST)

            try:
                OAuthUser.objects.create(user_id=user.id,
                                         openid=open_id,
                                         access_token=access_token,
                                         expires_in=expires_in,
                                         refresh_token=refresh_token)
            except:
                return Response("关联QQ用户失败", status=status.HTTP_400_BAD_REQUEST)

        # 生成jwt认证
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        try:
            avatar = user.avatar.url
        except:
            avatar = user_avatar

        user_info = {
            "token": token,
            "id": user.id,
            "username": user.username,
            "avatar": avatar,
            "nickname": nickname,
        }
        return Response({"user_info": user_info, "status": 1})
Пример #17
0
    def post(self, request):
        """显示注册处理"""

        # 接收数据
        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        cpassword = request.POST.get('cpwd')
        receiver = request.POST.get('receiver')
        phone = request.POST.get('phone')
        addr = request.POST.get('addr')
        email = request.POST.get('email')
        sex = request.POST.get('sex')
        mjsj = request.POST.get('mjsj')
        img = request.FILES.get('file')

        # 校验数据
        if not all([
                username, password, cpassword, receiver, phone, addr, email,
                sex, mjsj, img
        ]):
            # 缺少相关数据
            return render(request, 'register.html', {'errmsg': '缺少相关数据'})

        rec = FastDFSStorage().save(img.name, img)

        # 校验密码是否一致
        if not (password == cpassword):
            # 两次输入密码不一致
            return render(request, 'register.html', {'errmsg': '两次输入密码不一致'})

        # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',
                        email):
            # 邮箱不规范
            return render(request, 'register.html', {'errmsg': '邮箱不规范'})

        # 校验用户名是否重复
        if common.verify_exist(request, 'username', username):
            return render(request, 'register.html', {'errmsg': '用户名已存在'})

        # 校验手机号码是否重复
        if common.verify_exist(request, 'phone', phone):
            return render(request, 'register.html', {'errmsg': '手机号码已存在'})

        # 校验邮箱是否重复
        if common.verify_exist(request, 'email', email):
            return render(request, 'register.html', {'errmsg': '邮箱已存在'})

        # 业务处理
        # user表添加数据
        user = User.objects.create_user(username, email, password)
        # 1:男 0:女
        user.sex = sex
        # 0:买家 1:商家
        user.is_staff = mjsj
        user.phone = phone
        user.real_name = receiver

        # 读取上传的文件中的file项为二进制文件
        # file_content = ContentFile(img.read())
        # user.image.save(img.name, file_content)
        user.is_active = 0  # 设置为未激活状态
        user.save()

        # 处理发送邮件
        # 加密用户的身份信息,生成激活token
        serializer = TJSS(settings.SECRET_KEY, 900)
        info = {'confirm': user.id}
        token = serializer.dumps(info)
        # 默认解码为utf8
        token = token.decode()
        # 使用celery发邮件
        send_activate_email.delay(email, username, token)

        # address表添加数据
        address = Address()
        address.receiver = receiver
        address.phone = phone
        address.addr = addr
        address.is_default = True
        address.user = user
        lat_lng = common.get_lng_lat(addr)
        address.lat = lat_lng['lat']
        address.lng = lat_lng['lng']
        address.save()

        # user_image 表添加数据
        user_image = UserImage()
        user_image.user = user
        user_image.image = rec
        user_image.save()

        # 返回响应
        if int(mjsj):
            # 店铺注册页面
            return render(request, 'sj_register.html', {'user': user.id})
            # return redirect(reverse('user:sj_register'))
        else:
            # 买家登录页面
            # return render(request, 'login.html', locals())
            return redirect(reverse('user:login'))