Exemplo n.º 1
0
    def create(self, request, format='json'):
        serializer = UserCreateSerializer(data=request.data,
                                          context={'request': request})
        if serializer.is_valid():
            user = serializer.save()
            if user:
                token = Token.objects.create(user=user)
                jsonResponse = serializer.data
                jsonResponse['token'] = token.key
                return Response(jsonResponse, status=status.HTTP_201_CREATED)

        #Om vi får felmeddelanden vill frontend inte ha dessa som listor utan i strängar
        jsonErrors = serializer.errors
        try:
            old_data = jsonErrors.pop('username')
            jsonErrors[
                "username"] = "******"
        except:
            pass
        try:
            old_data = jsonErrors.pop('email')
            jsonErrors[
                'email'] = "This email is either invalid or already in use"
        except:
            pass
        try:
            old_data = jsonErrors.pop('password')
            jsonErrors['password'] = "******"
        except:
            pass

        return Response(jsonErrors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
    def post(self, request, format=None):
        serializer = UserCreateSerializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        if serializer.validated_data["terms_and_condition"] is False:
            data = {
                "error" : "Please accept the terms and condtions"
            }
            raise ValidationError(data)
        #Hash the password
        user = serializer.save(is_active=False, password=make_password(serializer.validated_data["password"]))

        current_site = get_current_site(request)
        mail_subject = 'Activate your account.'
        message = render_to_string('acc_active_email.html', {
            'user': user,
            'domain': current_site.domain,
            'uid':urlsafe_base64_encode(force_bytes(user.pk)),
            'token':account_activation_token.make_token(user),
        })
        to_email = user.email
        email = EmailMessage(
                    mail_subject, message, to=[to_email]
        )
        email.send()
        data = {
            "user_details" : serializer.data, 
            "message" : "A confirmation email has been sent on %s"%(user.email),
        }
        return Response(data=data)
Exemplo n.º 3
0
 def post(self, request, args):
     login_type = args["login_type"]
     code = args.get("code", None)
     phone = args.get("phone", None)
     pwd = args.get("password", None)
     sms_code = args.get("sms_code", None)
     # 若登录方式为微信
     if login_type == UserLoginType.WX:
         if not code:
             return self.send_fail(error_text="微信登录缺少code")
     # 若登录方式为密码
     elif login_type == UserLoginType.PWD:
         if not phone and not pwd:
             return self.send_fail(error_text="密码登录缺手机号或密码")
         success, user = get_user_by_phone_and_password(
             phone, pwd, login_type)
         if not success:
             return self.send_fail(error_text=user)
         token, refresh_token = self._set_current_user(user)
         response_data = jwt_response_payload_handler(
             token, refresh_token, user, request)
         return self.send_success(data=response_data)
     # 若登陆方式为手机号
     else:
         if not phone and not sms_code:
             return self.send_fail(error_text="密码登录缺手机号或验证码")
         redis_conn = get_redis_connection("verify_codes")
         real_sms_code = redis_conn.get("sms_%s" % phone)
         if not real_sms_code:
             return self.send_fail(error_text="验证码已过期")
         if str(real_sms_code.decode()) != sms_code:
             return self.send_error(status_code=status.HTTP_400_BAD_REQUEST,
                                    error_message={"detail": "短信验证码错误"})
         success, user = get_user_by_phone(phone, login_type)
         if not success:
             return self.send_fail(error_text=user)
         # user不存在,进行注册
         if not user:
             data = {
                 "phone":
                 phone,
                 "username":
                 phone,
                 "nickname":
                 "用户{phone}".format(phone=phone),
                 "head_image_url":
                 "http://img.senguo.cc/FlMKOOnlycuoZp1rR39LyCFUHUgl"
             }
             serializer = UserCreateSerializer(data=data)
             serializer.is_valid()
             user = serializer.save()
         token, refresh_token = self._set_current_user(user)
         response_data = jwt_response_payload_handler(
             token, refresh_token, user, request)
         return self.send_success(data=response_data)
Exemplo n.º 4
0
    def create(self, request, *args, **kwargs):
        password = request.data.get("password")
        user = {
            "username": request.data.get("username"),
            "nickname": request.data.get("nickname"),
            "password": make_password(password) if password else make_password("qa123456")
        }
        role_names = request.data.get("roleNames")
        if "管理员" in role_names:
            user["is_staff"] = True
        else:
            user["is_staff"] = False
        user_create_serializer = UserCreateSerializer(data=user)
        user_create_serializer.is_valid(raise_exception=True)
        user_create_serializer.save()
        user_id = User.objects.get(username=user["username"]).id

        user_role = {
            "user_id": user_id,
            "role_id": ""
        }
        for role_name in role_names:
            role_id = Role.objects.get(name=role_name).id
            user_role["role_id"] = role_id
            user_role_serializer = UserRoleSerializer(data=user_role)
            user_role_serializer.is_valid(raise_exception=True)
            user_role_serializer.save()

        return Response(user_create_serializer.data, status=status.HTTP_201_CREATED)
Exemplo n.º 5
0
 def post(self, request, *args, **kwargs):
     data = request.data
     if not request.data.get('display_name'):
         raise ValidationError({'detail': 'You have to give display name'})
     data['username'] = data['display_name']
     serializer = UserCreateSerializer(data=data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     usr_obj = MyUser.objects.filter(id=serializer.data['id']).first()
     serializer = UserListSerializer(usr_obj)
     return Response(serializer.data, status=200)
Exemplo n.º 6
0
 def post(self, request, args, shop_code):
     self._set_current_shop(request, shop_code)
     shop = self.current_shop
     phone = args.get("phone")
     sms_code = args.get("sms_code")
     # 验证密码是否一致
     if args.get("password1") != args.get("password2"):
         return self.send_fail(error_text="两次输入的密码不一致")
     # 校验验证码
     redis_conn = get_redis_connection("verify_codes")
     real_sms_code = redis_conn.get("sms_%s" % phone)
     if not real_sms_code:
         return self.send_fail(error_text="验证码已过期")
     if str(real_sms_code.decode()) != sms_code:
         return self.send_error(status_code=status.HTTP_400_BAD_REQUEST,
                                error_message={"detail": "短信验证码错误"})
     data = {
         "phone": phone,
         "username": phone,
         "nickname": "用户{phone}".format(phone=phone),
         "head_image_url":
         "http://img.senguo.cc/FlMKOOnlycuoZp1rR39LyCFUHUgl",
         "password": args.get("password1")
     }
     serializer = UserCreateSerializer(data=data)
     serializer.is_valid()
     user = serializer.save()
     customer = get_customer_by_user_id_and_shop_id_interface(
         user.id, shop.id)
     # 新客户则创建客户信息
     if not customer:
         create_customer(user.id, shop.id)
     token, refresh_token = self._set_current_user(user)
     response_data = jwt_response_payload_handler(token, refresh_token,
                                                  user, request)
     return self.send_success(data=response_data)
Exemplo n.º 7
0
 def post(self, request, args, shop_code):
     login_type = args["login_type"]
     code = args.get("code", None)
     phone = args.get("phone", None)
     pwd = args.get("password", None)
     sms_code = args.get("sms_code", None)
     self._set_current_shop(request, shop_code)
     shop = self.current_shop
     # todo 微信登录还需要修改
     # 若登录方式为微信
     if login_type == UserLoginType.WX:
         if not code:
             return self.send_fail(error_text="微信登录缺少code")
         shop_appid = MP_APPID
         shop_appsecret = MP_APPSECRET
         wechat_oauth = WeChatOAuth(
             app_id=shop_appid,
             secret=shop_appsecret,
             redirect_uri="",
             scope="snsapi_userinfo",
         )
         try:
             wechat_oauth.fetch_access_token(code)
             user_info = wechat_oauth.get_user_info()
         except:
             return self.send_fail(error_text='获取微信授权失败')
         """
            user_info = {
                    "openid": "oMZbfv3iy12L1q1XGWpkko_P_YPI",
                    "nickname": "hpf",
                    "sex": 1,
                    "language": "zh_CN",
                    "city": "武汉",
                    "province": "湖北",
                    "country": "中国",
                    "headimgurl": "http://thirdwx.qlogo.cn/mmopen/vi_32/yctGCWkz1jI2ybfVe12KmrXIb9R89dfgnoribX9sG75hBPJQlsK30fnib9r4nKELHcpcXAibztiaHH3jz65f03ibOlg/132",
                    "privilege": [],
                    "unionid": "oIWUauOLaT50pWKUeNKhKP6W0WIU"
                }
         """
         user_info["headimgurl"] = user_info["headimgurl"].replace(
             "http://", "https://")
         user = get_user_by_wx_unionid(user_info.get("unionid"))
         if not user:
             new_user_info = {
                 "username": user_info.get('phone'),
                 "phone": user_info.get('phone'),
                 "sex": user_info.get('sex'),
                 "nickname": user_info.get("nickname"),
                 "realname": user_info.get("realname"),
                 "head_image_url": user_info.get("headimgurl"),
                 "wx_unionid": user_info.get("unionid"),
                 "wx_openid": user_info.get("openid"),
                 "wx_country": user_info.get("country"),
                 "wx_province": user_info.get("province"),
                 "wx_city": user_info.get("city"),
             }
             user_serializer = UserCreateSerializer(data=new_user_info)
             user = user_serializer.save()
         ret, user_openid = get_openid_by_user_id_and_appid(
             user.id, shop_appid)
         # 不存在则添加用户的openid
         if not ret:
             info = {
                 'user_id': user.id,
                 'mp_appid': shop_appid,
                 'wx_openid': user_info.get("openid"),
             }
             create_user_openid(**info)
     # 若登录方式为密码
     elif login_type == UserLoginType.PWD:
         if not phone and not pwd:
             return self.send_fail(error_text="密码登录缺手机号或密码")
         success, user = get_user_by_phone_and_password(
             phone, pwd, login_type)
         if not success:
             return self.send_fail(error_text=user)
     # 若登陆方式为手机号
     else:
         if not phone and not sms_code:
             return self.send_fail(error_text="密码登录缺手机号或验证码")
         redis_conn = get_redis_connection("verify_codes")
         real_sms_code = redis_conn.get("sms_%s" % phone)
         if not real_sms_code:
             return self.send_fail(error_text="验证码已过期")
         if str(real_sms_code.decode()) != sms_code:
             return self.send_error(status_code=status.HTTP_400_BAD_REQUEST,
                                    error_message={"detail": "短信验证码错误"})
         success, user = get_user_by_phone(phone, login_type)
         if not success:
             return self.send_fail(error_text=user)
         # user不存在
         if not user:
             return self.send_fail(error_text="该用户不存在")
     customer = get_customer_by_user_id_and_shop_id_interface(
         user.id, shop.id)
     # 新客户则创建客户信息
     if not customer:
         create_customer(user.id, shop.id)
     token, refresh_token = self._set_current_user(user)
     response_data = jwt_response_payload_handler(token, refresh_token,
                                                  user, request)
     return self.send_success(data=response_data)
Exemplo n.º 8
0
 def create(self, request, *args, **kwargs):
     serializer = UserCreateSerializer(data=request.data)
     if serializer.is_valid(raise_exception=True):
         serializer.save()
         return Response(data=serializer.data)
Exemplo n.º 9
0
 def post(self, request):
     serializer = UserCreateSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)