def login_view(request): if "timeout" in request.session: wait = ceil(request.session["timeout"] - time.time()) if wait > 0: raise Throttled(detail=f"AUTH.THROTTLED.{wait}") username = request.data.get("username", None) password = request.data.get("password", None) if username is None or password is None: raise AuthenticationFailed("AUTH.CREDENTIALS_NONEXISTENT") user = authenticate(username=username, password=password) if user is None: request.session["attempts"] = request.session.get("attempts", 0) + 1 if request.session["attempts"] >= 10: # exponential timeout for each failed login attempt past the 10th timeout = (1 << (request.session["attempts"] - 10)) * 60 request.session["timeout"] = time.time() + timeout raise Throttled(detail=f"AUTH.THROTTLED.{timeout}") raise AuthenticationFailed("AUTH.CREDENTIALS_INVALID") login(request, user) if "attempts" in request.session: del request.session["attempts"] if "timeout" in request.session: del request.session["timeout"] return Response(UserSerializer(user).data)
def reset_password_view(request): token = None if request.method == "GET": token = request.GET.get("token") elif request.method == "POST": token = request.data.get("token") if token is None: raise APIException("RESET.INVALID_TOKEN") try: timeout = int( token[64:], 16 ) # tokens are 64-character random bytes + hex-encoded time if int(timeout) - time.time() < 0: raise APIException("RESET.INVALID_TOKEN") except ValueError: raise APIException("RESET.INVALID_TOKEN") if request.method == "GET": try: user = SluglineUser.objects.get(password_reset_token=token) return Response(UserSerializer(user).data) except SluglineUser.DoesNotExist: raise APIException("RESET.INVALID_TOKEN") else: user = SluglineUser.objects.get(password_reset_token=token) serializer = UserSerializer( data={"password": request.data["password"]}, instance=user, partial=True ) serializer.is_valid() if len(serializer.errors): raise APIException(serializer.errors) else: user.password_reset_token = "" serializer.save() return Response(None)
def update_user(user, request): data = request.data # We set the partial flag as the front-end may not choose to update all fields at once serializer = UserSerializer(data=data, instance=user, partial=True) serializer.is_valid() # if we're changing roles, or password, confirm password if data.get("role") != user.role or "password" in data: confirm_password(request) if len(serializer.errors): raise APIException(serializer.errors) else: try: updated_user = serializer.save() if "password" in data: update_session_auth_hash(request, updated_user) return Response(serializer.data) except Exception: raise APIException("USER.COULD_NOT_UPDATE")
def post(self, request, *args, **kwargs): response = {'status_code': 200, "message": "注册成功"} username = request.data.get('username') email = request.data.get('email') user_obj = User.objects.filter(username=username) if not user_obj: # 反序列话 user = UserSerializer(data=request.data) if user.is_valid(): user.save() response['data'] = {'username': username, 'email': email} else: response['status_code'] = 400 response['message'] = '注册失败:无效的参数' else: response['status_code'] = 201 response['message'] = "用户已存在" return JsonResponse(response)
def thankYouPage(request): output_json = {} if request.method == 'POST' and request.FILES['photo']: input_json = request.POST.dict() try: insert_param = {} insert_param['name'] = input_json['name'] insert_param['phone_id'] = input_json['phone'] insert_param['email'] = input_json['email'] insert_param['photo'] = request.FILES['photo'] insert_param['account_type'] = input_json['status'] serialized_user_params = UserSerializer(data=insert_param) if serialized_user_params.is_valid(raise_exception=True): serialized_user_params.save() output_json['Status'] = "Success" output_json['Message'] = "Data has been insert successfully" except Exception as ex: output_json['Status'] = "Failure" output_json[ 'Message'] = "Data could not be inserted successfully" + str( ex) output_json['Payload'] = str(ex) return render(request, 'thankyou.html', output_json)
def current_user_view(request): if request.user.is_authenticated: if request.method == "GET": return Response(UserSerializer(request.user).data) else: if ( not request.user.is_staff and not request.user.at_least(EDITOR_GROUP) and any(["role" in request.data]) ): raise APIException("USER.INSUFFICIENT_PRIVILEGES") return update_user(request.user, request) else: return Response(None)
def all_User(request): output_json = {} output_json['Payload'] = {} user_info_obj = None # import pdb ; pdb.set_trace() try: if request.method == 'GET': user_info_obj = user.objects.all() else: user_info_obj = user.objects.filter( status=request.POST.get('status', None)) user_info = UserSerializer(user_info_obj, many=True).data user_info_list = [] for item in user_info: user_info = {} user_info['profile_id'] = item.get('profile_id', None) user_info['name'] = item.get('name', None) user_info['phone_id'] = item.get('phone_id', None) user_info['email'] = item.get('email', None) user_info['photo'] = item.get('photo', None) user_status = account.objects.filter( account_id=item.get('account_type', None), isactive=True).values('account_name') user_info['account_type'] = user_status[0]['account_name'] user_info['status'] = item.get('status', None) datetime_object = datetime.strptime( str( item.get('last_modified_date', None).replace('T', ' ').replace('Z', '')), '%Y-%m-%d %H:%M:%S.%f') time_zone = pytz.timezone('Asia/Calcutta') user_info['added_date'] = time_zone.localize(datetime_object) user_info['last_modified_date'] = time_zone.localize( datetime_object) user_info_list.append(user_info) output_json['Status'] = "Success" output_json['Message'] = "data has been insert successfully" output_json['Payload'] = user_info_list # output_json['account_status'] = get_account_status(request) except Exception as ex: output_json['Status'] = "Failure" output_json[ 'Message'] = "Data could not be fetched successfully" + str(ex) output_json['Payload'] = str(ex) return render(request, 'alluser.html', output_json)
def create(self, request, *args, **kwargs): if SluglineUser.objects.filter(username=request.data["username"]).exists(): raise APIException({"username": ["USER.USERNAME.ALREADY_EXISTS"]}) # max username length; https://docs.djangoproject.com/en/3.0/ref/contrib/auth/ if len(request.data["username"]) > 150: raise APIException({"username": ["USER.USERNAME.TOO_LONG"]}) if request.data["role"] != CONTRIBUTOR_GROUP: confirm_password(request) serializer = UserSerializer(data=request.data) serializer.is_valid() if len(serializer.errors): raise APIException(serializer.errors) else: try: serializer.save() return Response(status=status.HTTP_201_CREATED, data=serializer.data) except Exception: raise APIException("USER.COULD_NOT_CREATE")