Пример #1
0
 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
Пример #2
0
 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)
Пример #3
0
 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)
Пример #4
0
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)
Пример #5
0
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)
Пример #6
0
 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)
Пример #7
0
 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)
Пример #8
0
 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)
Пример #9
0
    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)
Пример #10
0
    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'})
Пример #11
0
    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)
Пример #12
0
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)
Пример #13
0
 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)
Пример #14
0
 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)
Пример #15
0
 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)
Пример #16
0
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)
Пример #17
0
 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)
Пример #18
0
 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)
Пример #19
0
 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)
Пример #20
0
 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)
Пример #21
0
 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)
Пример #22
0
 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)
Пример #23
0
 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)
Пример #24
0
    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)
Пример #25
0
 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)
Пример #26
0
 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("")
Пример #27
0
 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)
Пример #28
0
 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)
Пример #29
0
 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 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)
Пример #31
0
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)
Пример #32
0
 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)
Пример #33
0
 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)
Пример #34
0
 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
Пример #35
0
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
Пример #36
0
    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)
Пример #38
0
    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))
Пример #39
0
 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)
Пример #40
0
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 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)
Пример #42
0
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
Пример #43
0
 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)
Пример #44
0
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)
Пример #45
0
     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)
Пример #46
0
 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)
Пример #47
0
    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)
Пример #48
0
 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)
Пример #49
0
 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)
Пример #50
0
 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)
Пример #51
0
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)
Пример #52
0
 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)
Пример #53
0
	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)
Пример #54
0
 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)
Пример #55
0
    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)
Пример #56
0
 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)
Пример #57
0
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)
Пример #58
0
    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)
Пример #59
0
	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)