def get(self, request, *args, **kw): ip = kw.get('pk') kw['request'] = request ip_details_request = IPDetails(ip) result = DetailsSerializer(ip_details_request) if not request.session.get('alienvaultid'): traffic_details_request = TrafficDetails(request, ip) user = UserSerializer(traffic_details_request) user_serializer = UserSerializer(data=JSONParser().parse( BytesIO(JSONRenderer().render(user.data)))) user_serializer.is_valid() user_serializer.save() response = Response(result.data, status=status.HTTP_200_OK) return response
def post(self, request, format=None): queryset = Logistics_user.objects.all() serializer = UserSerializer(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)
def post(self, request, format=None): serializer = UserSerializer(data=request.DATA) if serializer.is_valid(): #serializer.data message = "from User2" return Response({"message": message, "data": serializer.data}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def login_handle(request, pk): try: user = UserInfo.objects.get(pk=pk) except user.DoesNotExist: return HttpResponse(status=404) # if request.method == 'POST': serializer = UserSerializer(user) return JSONResponse(serializer.data) # 获得指定用户的信息 elif request.method == 'GET': serializer = UserSerializer(user) return JSONResponse(serializer.data) # 修改指定用户的信息(忘记密码) elif request.method == 'PUT': data = JSONParser().parse(request) try: user = UserInfo.objects.get(pk=pk) except user.DoesNotExist: return HttpResponse(status=404) serializer = UserSerializer(user, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) # 删除指定用户信息 elif request.method == 'DELETE': user.delete() return HttpResponse(status=204)
def create_user(request): data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({'message': 'Created'}) return Response(serializer.errors)
def post(self,request, format=None): data = request.DATA graph = facebook.GraphAPI(data['token']) profile = graph.get_object("me") picture = graph.get_connections("me", "picture") objUser = {} objUser['first_name'] = profile['first_name'] objUser['last_name'] = profile['last_name'] objUser['email'] = profile['email'] objUser['username'] = profile['id'] objUser['is_active'] = True objProfile = {} objProfile['access_token'] = data['token'] objProfile['profile_picture'] = picture['url'] objProfile['gender'] = profile['gender'] objUser['user_profile'] = objProfile user = UserSerializer() serializer = UserSerializer(data=objUser) try: userobj = User.objects.get(username=objUser['username']) return Response(objUser, status=status.HTTP_200_OK) except User.DoesNotExist: 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)
def post(self, request, format=None): #Si existe el usuario dar mensaje de error de que ya existe. serializer = UserSerializer(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)
def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer_context = { 'request': Request(request), } user_data = {} user_data['email'] = request.data.pop('email')[0] user_data['username'] = request.data.pop('username')[0] user_data['password'] = request.data.pop('password')[0] user_data['first_name'] = request.data.pop('first_name')[0] user_seriliazer = UserSerializer(data=user_data) if user_seriliazer.is_valid(request.data): user = user_seriliazer.save() request.data['user'] = user.id serializer = SBUserSerializer(data=request.data, context=serializer_context) if serializer.is_valid(): employee = serializer.save() if request.data.get('user_type') == 'EMPLOYEE': EmployeeRole.objects.create( employee=employee, department=Department.objects.get( pk=request.data.get('department')), role=request.data.get('role')) return Response(serializer.data, status=status.HTTP_201_CREATED) else: user.delete() return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): """ Creates a new account :param request: { "username": "******", "first_name": "string", "last_name": "string", "password": "******", "email": "string", "user_type": integer, "access_level": integer, "company_id": integer, "invite_id": integer } :return: {message: string, user: UserSerializer, data: DataSerializer} """ data = json.loads(request.body) user = UserSerializer(data=data) if user.is_valid(): saved_user = user.save() try: userdata = Data.objects.create( user=saved_user, user_type=data.get('user_type'), access_level=1, company_id=data.get('company_id')) # if the user is a Client, test if it is the first one of that company # to change ownership if data.get('user_type') == Data.CLIENT: company = Company.objects.get(id=data.get('company_id')) if company.owner is None: company.owner = saved_user company.save() userdata.access_level = Data.ADMIN userdata.save() if data.get('invite_id', None): invite = Invite.objects.get(id=data.get('invite_id')) invite.accepted = True invite.save() return Response( { 'message': 'User created successfully', 'user': user.data, 'data': DataSerializer(userdata).data }, status.HTTP_201_CREATED) except Exception as e: saved_user.delete() return Response({'message': 'User couldnt be created'}, status=status.HTTP_400_BAD_REQUEST) return Response({'message': 'User could not be created'})
def create(self, request, *args, **kwargs): """ """ app = None try: app = Application.objects.get(client_id=self.kwargs['client_id']) except Application.DoesNotExist: return Response({ 'message': 'Invalid client_id.' }, status=status.HTTP_400_BAD_REQUEST) serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.create() application_user = ApplicationUser(application=app, user=user) application_user.save() 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}, status=status.HTTP_201_CREATED) else: return Response({ 'data': serializer.errors, 'message': 'User could not be created with the received data.' }, status=status.HTTP_400_BAD_REQUEST)
def user_signup(request): data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def patch(self, request): serialized = UserSerializer(data=request.DATA) if serialized.is_valid(): serialized.save() return Response(status=status.HTTP_205_RESET_CONTENT) else: return Response(serialized.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.DATA) # en lugar request.POST if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): kwargs = serializer.validated_data user_data = User(**kwargs) print datetime.now(pytz.timezone('America/Phoenix')) user_data.creationTime = datetime.now( pytz.timezone('America/Phoenix')) global condition_url city_data = City.objects.filter(id=self.request.data['cityId']) if city_data is not None: name = city_data[0].name state = city_data[0].state request_URL = condition_url + state.replace( " ", "_") + "/" + name.replace(" ", "_") + ".json" print request_URL request_data = requests.get(request_URL) request_json = json.loads(request_data.content) user_data.timezone = request_json['current_observation'][ 'local_tz_short'] else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) user_data.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def userEdit(request): try: print request.data serializer = UserSerializer(data=request.data) if serializer.is_valid(): #print "valid" #print serializer.data return Response( { 'status': True, 'data': None, 'message': 'Updated' }, status=status.HTTP_200_OK) else: return Response( { 'status': False, 'data': None, 'message': serializer.errors }, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({ 'status': False, 'data': None, 'message': str(e) }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) else: return Response(serializer.errors, status=400)
def put(self, request, pk, format=None): user = Logistics_user.objects.get(pk=pk) serializer = UserSerializer(user, data=request.data)#, many=True, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def createUser(self, request): data = JSONParser.parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400)
def put(self, request, id, format=None): snippet = self.get_object(id=id) serializer = UserSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request): """ """ # Si cambia el email puede generar problemas serios, por eso se retorna # un nuevo token decoded_token = decode_token(request.META) serializer = UserSerializer( MyUser.objects.get(email=decoded_token['email']), data=request.data, partial=True) if serializer.is_valid(): user = serializer.save() 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}, status=status.HTTP_200_OK) else: return Response({ 'data': serializer.errors, 'message': 'User could not be created with the received data.' }, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = UserSerializer(data=request.DATA) if serializer.is_valid(): # los serializer funcionan como los djangoforms, así que hay que validarlo serializer.save() # guardamos en la base de datos el nuevo usuario return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, *args, **kwargs): git_baseurl = "https://api.github.com/search/users?q=" context = {} git_baseurl = git_baseurl + (request.GET.get('name') if request.GET.get('name') else '') git_baseurl = git_baseurl + ("+type:" + request.GET.get('type') if request.GET.get('type') else '') #tin= request.GET['in'] repos = request.GET.get('repos') if request.GET.get('repos') else 0 location = request.GET.get('location') if request.GET.get( 'location') else '' language = request.GET.get('language') if request.GET.get( 'language') else '' created = request.GET.get('created') if request.GET.get( 'created') else '' followers = request.GET.get('followers') if request.GET.get( 'followers') else 0 if repos != 0: git_baseurl = git_baseurl + "+repos:>" + str(repos) if location != '': git_baseurl = git_baseurl + "+location:" + location if language != '': git_baseurl = git_baseurl + "+language:" + language if created != '': git_baseurl = git_baseurl + "+created:" + created if followers != 0: git_baseurl = git_baseurl + "+followers:>" + followers print git_baseurl headers = {'Accept': 'application/vnd.github.v3.text-match+json'} r = requests.get(git_baseurl, headers=headers) response_users = r.json()['items'] for r_user in response_users: r_user['repos'] = repos r_user['location'] = location r_user['language'] = language r_user['created'] = created r_user['followers'] = followers r_user['name'] = '' r_user['email'] = '' for text_match in r_user['text_matches']: if text_match['property'] == 'name': r_user['name'] = text_match['fragment'] elif text_match['property'] == 'email': r_user['email'] = text_match['fragment'] r_user['git_id'] = r_user['id'] serializer = UserSerializer(data=r_user) try: gituser = GitUser.objects.get(git_id=r_user['id']) serializer.update(gituser, r_user) continue except: print("Unexpected error:", sys.exc_info()[0]) print("Unexpected error:", sys.exc_info()[1]) pass if serializer.is_valid(): serializer.save() else: print "data not valid" return HttpResponse("")
def create(self, request): serializer = UserSerializer(data=request.DATA) # en lugar request.POST if serializer.is_valid(): new_user = serializer.save() self.send_welcome_email(new_user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() Player.objects.create(user_id=serialized.data['id']) return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
def register(request): serialized = {} user_data = {} if request.META['CONTENT_TYPE'] == 'application/json': serialized = UserSerializer(data=request.DATA) if serialized.is_valid(): user_data = request.DATA elif request.META['CONTENT_TYPE'] == 'application/x-www-form-urlencoded': serialized = UserSerializer(data=request.POST) if serialized.is_valid(): user_data = utils.get_user_data(request.POST) if serialized.is_valid(): utils.create_inactive_user(**user_data) return Response(utils.USER_CREATED_RESPONSE_DATA, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
def modifyUserInfo(request): if request.method == 'POST': serializer = UserSerializer(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)
def post(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = authenticate(username=serializer.data['username'], password=serializer.data['password']) if user: token = Token.objects.get_or_create(user=user) return Response({'token': token[0].key, 'id': user.id}) return Response({'errors': 'Username/Password is not correct'}, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, *args, **kw): ip = kw.get('pk') kw['request'] = request ip_details_request = IPDetails(ip) result = DetailsSerializer(ip_details_request) if not request.session.get('alienvaultid'): traffic_details_request = TrafficDetails(request, ip) user = UserSerializer(traffic_details_request) user_serializer = UserSerializer( data=JSONParser().parse( BytesIO(JSONRenderer().render(user.data)) ) ) user_serializer.is_valid() user_serializer.save() response = Response(result.data, status=status.HTTP_200_OK) return response
def authenticate_ldap(username, password, token): connection = ldap.initialize("ldap://ldap.iitb.ac.in") search_result = connection.search_s( 'dc=iitb,dc=ac,dc=in', ldap.SCOPE_SUBTREE, 'uid=%s' % username, ['uid', 'cn', 'givenName', 'sn', 'mail', 'employeeNumber']) response_data = { 'error': False, 'error_message': "", 'first_name': "", 'last_name': "", 'email': "", 'employeeNumber': "", 'ldap': "", 'name': "", 'token': "", } if len(search_result) < 1 or search_result[0][1]['uid'][0] != username: response_data['error'] = True response_data['error_message'] = "Invalid Username/Password" else: try: bind_ds = search_result[0][0] connection.bind_s(bind_ds, password) response_data['error'] = False result_dict = search_result[0][1] response_data['first_name'] = result_dict['givenName'][0] response_data['last_name'] = result_dict['sn'][0] response_data['name'] = result_dict['cn'][0] response_data['email'] = result_dict['mail'][0] response_data['ldap'] = result_dict['uid'][0] response_data['employeeNumber'] = result_dict['employeeNumber'][0] user_serialized = UserSerializer(data=response_data) if user_serialized.is_valid(): user = user_serialized.save() user.backend = "django.contrib.auth.backends.ModelBackend" response_data['id'] = user.id if token: user_token = UserToken(user=user) user_token.save() response_data['token'] = user_token.token.hex return response_data, user else: response_data['error'] = True response_data[ 'error_message'] = 'Unable to login. Please contact admin' except ldap.INVALID_CREDENTIALS: response_data['error'] = True response_data['error_message'] = "Invalid Credentials" except: response_data['error'] = True response_data['error_message'] = 'Unable to authenticate' return response_data, None
def post(self, request, format=None, sport=None): try: email = request.data['email'] existing_user = User.objects.get(email=email) return Response(error_response( 'User with email %s already exists.' % email), status=status.HTTP_400_BAD_REQUEST) except: pass sport = int(request.query_params.get('sport', '0')) user = UserSerializer() user_fields = [key for key in user.get_fields().keys()] user_data = { key: request.data[key] for key in user_fields if key in request.data } user_data['type_id'] = SPORTS[sport][1] user_serializer = UserSerializer(data=user_data) # Create base user if user_serializer.is_valid(): if not 'password' in request.data: return Response(error_response('Password not provided.'), status=status.HTTP_400_BAD_REQUEST) else: user = user_serializer.save() user.set_password(request.data['password']) user.save() # Create specific user (swimmer, runner...) if sport == 0: swimmer = SwimmerSerializer() swimmer_fields = [key for key in SwimmerSerializer.specific_fields] swimmer_data = { key: request.data[key] for key in swimmer_fields if key in request.data } swimmer_data['type'] = user.id serializer = SwimmerSerializer(data=swimmer_data) elif sport == 1: runner = RunnerSerializer() runner_fields = [key for key in RunnerSerializer.specific_fields] runner_data = { key: request.data[key] for key in runner_fields if key in request.data } runner_data['type'] = user.id serializer = RunnerSerializer(data=runner_data) if serializer.is_valid(): sport_user = serializer.save() return Response(success_response(serializer.data), status=status.HTTP_201_CREATED) return Response(error_response(serializer.errors), status=status.HTTP_400_BAD_REQUEST)
def register(request): serialized = UserSerializer(data=request.POST) if serialized.is_valid(): user_data = utils.get_user_data(request.POST) utils.create_inactive_user(**user_data) return Response(utils.USER_CREATED_RESPONSE_DATA, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
def _test_google_auth(self): auth_token = confidential.google_auth_token client = APIClient() request = client.post('user/google_auth/',data={'auth_token':auth_token}) self.assertEqual(request.status_cod, status.HTTP_200_OK) serializer = UserSerializer(data=request.data) self.assertTrue(serializer.is_valid(raise_exception=False))
def put(self, request, pk, format=None): user = Logistics_user.objects.get(pk=pk[0]) serializer = UserSerializer( user, data=request.data) #, many=True, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def register(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse({'success': True}) else: return JsonResponse({'success': False})
def authenticate_ldap(username, password, token): connection = ldap.initialize("ldap://ldap.iitb.ac.in") search_result = connection.search_s('dc=iitb,dc=ac,dc=in', ldap.SCOPE_SUBTREE, 'uid=%s' % username, ['uid', 'cn', 'givenName', 'sn', 'mail', 'employeeNumber']) response_data = { 'error': False, 'error_message': "", 'first_name': "", 'last_name': "", 'email': "", 'employeeNumber': "", 'ldap': "", 'name': "", 'token': "", } if len(search_result) < 1 or search_result[0][1]['uid'][0] != username: response_data['error'] = True response_data['error_message'] = "Invalid Username/Password" else: try: bind_ds = search_result[0][0] connection.bind_s(bind_ds, password) response_data['error'] = False result_dict = search_result[0][1] response_data['first_name'] = result_dict['givenName'][0] response_data['last_name'] = result_dict['sn'][0] response_data['name'] = result_dict['cn'][0] response_data['email'] = result_dict['mail'][0] response_data['ldap'] = result_dict['uid'][0] response_data['employeeNumber'] = result_dict['employeeNumber'][0] user_serialized = UserSerializer(data=response_data) if user_serialized.is_valid(): user = user_serialized.save() user.backend = "django.contrib.auth.backends.ModelBackend" response_data['id'] = user.id if token: user_token = UserToken(user=user) user_token.save() response_data['token'] = user_token.token.hex return response_data, user else: response_data['error'] = True response_data['error_message'] = 'Unable to login. Please contact admin' except ldap.INVALID_CREDENTIALS: response_data['error'] = True response_data['error_message'] = "Invalid Credentials" except: response_data['error'] = True response_data['error_message'] = 'Unable to authenticate' return response_data, None
def post(self, request, *args, **kwargs): ser = UserSerializer(data=request.POST) if ser.is_valid(): user = ser.save() auth.login(request, user) if request.accepted_renderer.format == "html": return redirect("/") else: return Response(ser.data) return Response(ser.errors)
def register(request): serialized = UserSerializer(data=request.DATA) if serialized.is_valid(): get_user_model().objects.create_user( serialized.init_data['email'], 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 put(self,request,pk): user = get_object_or_404(User,pk=pk) serializer = UserSerializer(user,data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_200_OK) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def post(self, request): # Para crear un usuario # Hay que pasar request.DATA en vez de request.POST serializer = UserSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: # Algo ha ido mal return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None, sport=None): try: email = request.data['email'] existing_user = User.objects.get(email=email) return Response(error_response('User with email %s already exists.' % email), status=status.HTTP_400_BAD_REQUEST) except: pass sport = int(request.query_params.get('sport', '0')) user = UserSerializer() user_fields = [key for key in user.get_fields().keys()] user_data = { key: request.data[key] for key in user_fields if key in request.data } user_data['type_id'] = SPORTS[sport][1] user_serializer = UserSerializer(data=user_data) # Create base user if user_serializer.is_valid(): if not 'password' in request.data: return Response(error_response('Password not provided.'), status=status.HTTP_400_BAD_REQUEST) else: user = user_serializer.save() user.set_password(request.data['password']) user.save() # Create specific user (swimmer, runner...) if sport == 0: swimmer = SwimmerSerializer() swimmer_fields = [key for key in SwimmerSerializer.specific_fields] swimmer_data = { key: request.data[key] for key in swimmer_fields if key in request.data } swimmer_data['type'] = user.id serializer = SwimmerSerializer(data=swimmer_data) elif sport == 1: runner = RunnerSerializer() runner_fields = [key for key in RunnerSerializer.specific_fields] runner_data = { key: request.data[key] for key in runner_fields if key in request.data } runner_data['type'] = user.id serializer = RunnerSerializer(data=runner_data) if serializer.is_valid(): sport_user = serializer.save() return Response(success_response(serializer.data), status=status.HTTP_201_CREATED) return Response(error_response(serializer.errors), status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk): user = get_object_or_404(User, pk=pk) if request.user.is_superuser or request.user == user: serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(status=status.HTTP_404_NOT_FOUND)
def put(self, request, pk): user = self.get_object(pk) if request.user.has_perm("umaa.edit_user") or request.user == user: serializer = UserSerializer(user, data=request.DATA, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(UNAUTHORIZED_MSG, status=status.HTTP_401_UNAUTHORIZED)
def put(self, request, pk): user = self.get_object(pk) if request.user.has_perm('umaa.edit_user') or request.user == user: serializer = UserSerializer(user, data=request.DATA, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response(UNAUTHORIZED_MSG, status=status.HTTP_401_UNAUTHORIZED)
def users(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) else: return JSONResponse(serializer.errors, status=400) return HttpResponse(status=400)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) print request.data if serializer.is_valid(): user = authenticate(username=serializer.data['username'], password=serializer.data['password']) if user: if user.first_name == 'facebook': return Response({'errors': 'Facebook User'}, status=status.HTTP_400_BAD_REQUEST) token = Token.objects.get_or_create(user=user) return Response({'token': token[0].key}) return Response({'errors': 'Username/Password is not correct'}, status=status.HTTP_400_BAD_REQUEST)
def put(self,request, pk): user = get_object_or_404(User, pk=pk) if request.user.is_superuser or request.user == user: serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=202) else: return Response(serializer.errors,status=400) else: return Response(status=status.HTTP_404_NOT_FOUND)
def put(self, request, pk): user = get_object_or_404(User, pk=pk) serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk): user = get_object_or_404(User, pk=pk) if request.user.is_superuser or request.user == user: serializer = UserSerializer(user, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=202) else: return Response(serializer.errors, status=400) else: return Response(status=status.HTTP_404_NOT_FOUND)
def post(self, request, format='json'): serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: token = Token.objects.create(user=user) json = serializer.data json['token'] = user return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): try: user = User.objects.get(username=serializer.data['username']) except ObjectDoesNotExist: user = User.objects.create_user(serializer.data['username'], password=serializer.data['password']) user.save() token = Token.objects.create(user=user) return Response({'token': token.key}, status=status.HTTP_201_CREATED) return Response({'errors': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) return Response({'errors': 'Fields may not be blank'}, status=status.HTTP_400_BAD_REQUEST)