def login(request): # POST if request.method == 'POST': # JSONをパース data = JSONParser().parse(request) # Userモデルに当てはめる serializer = UserSerializer(data=data) # 有効なものかを判断する if serializer.is_valid(): try: # ユーザーを取得 user = UserSerializer.select( user_name=serializer.initial_data["account_name"]) except: return HttpResponse("ユーザーが存在しません", status=401) # ログイン成功時 if check_password(serializer.data["password"], user.password): # トークン生成 token = TokenSerializer.create(user) # ユーザーにトークンを渡す data = '{"token": "' + token + '"}' response = HttpResponse(data, status=200) response['content-type'] = 'application/json; charset=utf-8' return response # ログイン失敗時 else: return HttpResponse("ログイン失敗", status=401) # 不正なリクエスト return HttpResponse("不正なリクエスト", status=400) else: return HttpResponse("不正なリクエスト", status=400)
def post(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() return Response({ 'response': 'Регистрация прошла успешно!', 'first_name': user.first_name, 'last_name': user.last_name }) else: return Response({serializer.errors})
def post(self, request, *args, **kwargs): serialized = UserSerializer(data=request.data) if serialized.is_valid(): User.objects.create_user( serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'] ) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, pk): file_id = self.kwargs['pk'] file = get_object_or_404(SharedFile, pk=file_id) if request.user == file.user_id or request.user.has_perm( 'webapp.change_sharedfile'): serializer = UserSerializer(data=request.data, partial=True) if serializer.is_valid(): user_id = request.data['id'] user = get_object_or_404(User, pk=user_id) file.privately_accessed.remove(user) return JsonResponse(data=request.data) else: return JsonResponse({'message': 'Доступ ограничен'}, status=403)
def cache_api(request: object) -> object: if request.method == 'POST' and request.is_ajax: data: dict = json.loads(request.body.decode('UTF-8')) user_id: str = data['id'] if not user_id: return JsonResponse({'error': "Id is not defined"}, status=400) user: dict = redis.get(user_id, json=True, prefix=get_db_table_name(get_user_model())) if user: return JsonResponse({'redis': user}, status=200) else: user = get_user_model().objects.get(id=user_id) user_json = UserSerializer(user).data redis.set(name=user_id, value=user_json, json=True, prefix=get_db_table_name(get_user_model()), ex=10) return JsonResponse({'django': user_json}, status=200) return JsonResponse({"error": "method must be post"}, status=400)
def cache_user(sender, instance, *args, **kwargs): obj_json = UserSerializer(instance).data prefix = get_db_table_name(User) redis.set(name=obj_json['id'], value=obj_json, json=True, prefix=prefix, ex=60)
def patch(self, request, pk): file_id = self.kwargs['pk'] file = get_object_or_404(SharedFile, pk=file_id) if request.user == file.user_id or request.user.has_perm( 'webapp.change_sharedfile'): user_name = request.data['user_name'].strip() try: user = User.objects.get(username=user_name) if user in file.privately_accessed.all(): return JsonResponse( {'message': 'Пользователь уже добавлен'}, status=400) file.privately_accessed.add(user) serializer = UserSerializer(user) return JsonResponse(data=serializer.data) except ObjectDoesNotExist: return JsonResponse({'message': 'Пользователь не найден'}, status=404) else: return JsonResponse({'message': 'Доступ ограничен'}, status=403)
def register(request): # POST if request.method == 'POST': # JSONをパース data = JSONParser().parse(request) # Userモデルに当てはめる serializer = UserSerializer(data=data) # バリデーションを掛ける(パスワードはハッシュ化するので、空文字判定を先に行う) # パスワードが空かを確認する if serializer.initial_data["password"] == "": return HttpResponse("使用できないパスワードです。", status=403) # パスワードをハッシュ化 serializer.initial_data["password"] = make_password( serializer.initial_data["password"], hasher='argon2') # 有効なものかを判断する if serializer.is_valid(): # 保存 try: serializer.save() # ユーザーIDを取得 user = UserSerializer.select( user_name=serializer.initial_data["account_name"]) # トークン生成 token = TokenSerializer.create(user) # ユーザーにトークンを渡す data = '{"token": "' + token + '"}' response = HttpResponse(data, status=200) response['content-type'] = 'application/json; charset=utf-8' return response # account_nameがかぶったときなどのエラー処理 except Exception as e: print(e) return HttpResponse("ユーザー名が使われています", status=409) # 不正なリクエストの場合 return HttpResponse("不正なリクエスト", status=400) else: return HttpResponse("不正なリクエスト", status=400)
def post(self, request): """ Returns token for a registered user --- parameters: - name: email description: email used to register required: true type: string paramType: form - name: username description: username used to register required: true type: string paramType: form - name: password description: password used to register required: true type: string paramType: form - name: confirm_password description: confirmation password for user required: true type: string paramType: form """ data = request.data username = data.get('username') email = data.get('email') password = data.get('password') confirm_password = data.get('confirm_password') if not username: return Response({'message': 'Username not provided.'}, status=status.HTTP_400_BAD_REQUEST) if len(username) < 6: return Response({'message': 'Username is too short (Minimum is 6 characters)'}, status=status.HTTP_400_BAD_REQUEST) if not password: return Response({'message': 'Password not provided.'}, status=status.HTTP_400_BAD_REQUEST) if not confirm_password: return Response({'message': 'Please confirm your password.'}, status=status.HTTP_400_BAD_REQUEST) if len(password) < 6 or len(confirm_password) < 6: return Response({'message': 'Password is too short (Minimum is 6 characters)'}, status=status.HTTP_400_BAD_REQUEST) if password != confirm_password: return Response({'message': 'The passwords do not match'}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username): return Response({'message': 'Username already exist.'}, status=status.HTTP_400_BAD_REQUEST) if not email: return Response({'message': 'Email not provided.'}, status=status.HTTP_400_BAD_REQUEST) serializer = UserSerializer(data=data) #import ipdb; #ipdb.set_trace() if serializer.is_valid(): User.objects.create_user(username=username, password=password, email=email) return super(RegisterView, self).post(request) else: return Response({'message': 'Unable to register. Plese ensure ' \ 'you provide a valid email'}, status=status.HTTP_400_BAD_REQUEST)