def create(self, request): """ Create User Create new user """ serializer = UserCreateBody(data=request.data) if serializer.is_valid(raise_exception=True): username = serializer.validated_data.get("username") role = serializer.validated_data.get("role") organization = serializer.validated_data.get("organization") password = serializer.validated_data.get("password") email = serializer.validated_data.get("email") user_count = UserProfile.objects.filter( Q(username=username) | Q(email=email) ).count() if user_count > 0: raise ResourceExists( detail="User name or email already exists" ) user = UserProfile( username=username, role=role, email=email, organization=organization, ) user.set_password(password) user.save() response = UserIDSerializer(data={"id": user.id}) if response.is_valid(raise_exception=True): return Response( response.validated_data, status=status.HTTP_201_CREATED )
def getProfile(self,request): try: userProfile = UserProfile.objects.get(user = request.user.id) except Exception as e: userProfile = UserProfile(request.user.id) userProfile.save() return Response(UserProfileSerializer(userProfile).data)
def test_basic_operations(self): user_data = { "username":"******", "password":"******", "email" : "*****@*****.**" } #Create a userprofile user=User.objects.create_user(**user_data) profile = UserProfile(user=user, facebook_id=31337) profile.username = "******" #Set some properties patch = {"facebook_id":666} profile.set(**patch) #Get them, and check if they are returned self.assertEqual(profile.username,"jia200x") self.assertEqual(profile.user.username,"jia200x") self.assertEqual(profile.facebook_id,666)
def delete(self, request, pk): asker = UserProfile.get(request) result = asker.delete_project(pk) return Response(result)
def get(self, request, pk=None): asker = UserProfile.get(request) if pk: project = Project.objects.filter(pk=pk).first() if project: if not project.user and project.creator != asker and not project.is_series: ProjectShowing.objects.get_or_create(project_id=pk, user=asker, **request.data) page = project.page(asker) if page: return Response(page) result = { 'project': { 'id': None, 'title': None, 'days': {}, 'money': None, 'money_calculating': False, 'money_per_day': None, 'client': None, 'user': None, 'creator': ProfileItemShortSerializer(asker).data, 'canceled': None, 'is_paid': False, 'is_wait': True, 'info': None, 'parent': None, 'confirmed': False, 'is_series': False }, 'calendar': { 'days': {}, 'daysOff': [] } } user = UserProfile.get(request.GET.get('user')) series = Project.get(request.GET.get('series')) copy = Project.get(request.GET.get('copy')) if series: user = series.user series_fields = SeriesFillingSerializer(series).data result['project'].update(series_fields) result['project'].update({ 'is_series': False, 'parent': ProjectListItemSerializer(series).data }) if user: result['project'].update({ 'user': ProfileItemShortSerializer(user).data, 'is_wait': user != asker, 'confirmed': user == asker }) result['calendar'] = user.get_calendar(asker) if copy: page = copy.page(asker) if page: page['project']['id'] = None return Response(page) return Response(result)
def signup_user_view(request): # Si el usuario esta ya logueado, lo redireccionamos a home if request.user.is_authenticated(): return redirect(reverse('home')) if request.method == 'POST': # Si el method es post, obtenemos los datos del formulario form = SignupUserForm(request.POST, request.FILES) # Comprobamos si el formulario es valido if form.is_valid(): # En caso de ser valido, obtenemos los datos del formulario. # form.cleaned_data obtiene los datos limpios y los pone en un # diccionario con pares clave/valor, donde clave es el nombre del campo # del formulario y el valor es el valor si existe. cleaned_data = form.cleaned_data username = cleaned_data.get('username') password = cleaned_data.get('password') email = cleaned_data.get('email') phone = cleaned_data.get('phone') photo = cleaned_data.get('photo') # E instanciamos un objeto User, con el username y password user_model = User.objects.create_user(username=username, password=password) # Añadimos el email user_model.email = email # Y guardamos el objeto, esto guardara los datos en la db. user_model.save() # Ahora, creamos un objeto UserProfile, aunque no haya incluido # una imagen, ya quedara la referencia creada en la db. user_profile = UserProfile() # Al campo user le asignamos el objeto user_model user_profile.user = user_model # y le asignamos la photo (el campo, permite datos null) user_profile.photo = photo user_profile.phone = phone # Por ultimo, guardamos tambien el objeto UserProfile user_profile.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) else: pass #if he comes from new_sighting if 'session_id' in request.session: sighting_id = request.session['session_id'] s = Sighting.objects.get(id=sighting_id) s.user = user s.save() # Ahora, redireccionamos a la pagina home.html # Pero lo hacemos con un redirect. return redirect(reverse('home')) else: # Si el mthod es GET, instanciamos un objeto RegistroUserForm vacio form = SignupUserForm() # Creamos el contexto context = {'form': form} # Y mostramos los datos return render(request, 'signup.html', context)
def handle(self, *args, **options): username = options.get("username") password = options.get("password") role = options.get("role") email = options.get("email") is_superuser = options.get("is_superuser", False) force = options.get("force", False) try: user = UserProfile.objects.get(email=email) except ObjectDoesNotExist: user = UserProfile( username=username, role=role, email=email, is_superuser=is_superuser, ) user.set_password(password) user.save() else: if force: user.username = username user.role = role user.is_superuser = is_superuser user.set_password(password) user.save() self.stdout.write( self.style.SUCCESS("Create user successfully %s" % user.id) )
def signup_user_view(request): # Si el usuario esta ya logueado, lo redireccionamos a home if request.user.is_authenticated(): return redirect(reverse('home')) if request.method == 'POST': # Si el method es post, obtenemos los datos del formulario form = SignupUserForm(request.POST, request.FILES) # Comprobamos si el formulario es valido if form.is_valid(): # En caso de ser valido, obtenemos los datos del formulario. # form.cleaned_data obtiene los datos limpios y los pone en un # diccionario con pares clave/valor, donde clave es el nombre del campo # del formulario y el valor es el valor si existe. cleaned_data = form.cleaned_data username = cleaned_data.get('username') password = cleaned_data.get('password') email = cleaned_data.get('email') photo = cleaned_data.get('photo') # E instanciamos un objeto User, con el username y password user_model = User.objects.create_user(username=username, password=password) # Añadimos el email user_model.email = email # Y guardamos el objeto, esto guardara los datos en la db. user_model.save() # Ahora, creamos un objeto UserProfile, aunque no haya incluido # una imagen, ya quedara la referencia creada en la db. user_profile = UserProfile() # Al campo user le asignamos el objeto user_model user_profile.user = user_model # y le asignamos la photo (el campo, permite datos null) user_profile.photo = photo # Por ultimo, guardamos tambien el objeto UserProfile user_profile.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) else: pass #if he comes from new_sighting if 'session_id' in request.session: sighting_id = request.session['session_id'] s = Sighting.objects.get(id=sighting_id) s.user = user s.save() # Ahora, redireccionamos a la pagina home.html # Pero lo hacemos con un redirect. return redirect(reverse('home')) else: # Si el mthod es GET, instanciamos un objeto RegistroUserForm vacio form = SignupUserForm() # Creamos el contexto context = {'form': form} # Y mostramos los datos return render(request, 'signup.html', context)
def test_resource(self): client = self.client #test POST post_response = client.post(self.users_list_url, self.user_post_data) self.assertEqual(post_response.status_code, 201, post_response.content) #test matching GET get_response = client.get(self.users_list_url, parse='json') self.assertEqual(get_response.status_code, 200, get_response.content) userprofile_dict = get_response.data['objects'][0] userprofile_keys = userprofile_dict.keys() self.assertTrue('email' in userprofile_keys) self.assertTrue('facebook_id' in userprofile_keys) #test attempt unauthorized put put_data = dict(self.user_post_data) put_data['first_name'] = "darth" put_response = client.put(userprofile_dict['resource_uri'], put_data) self.assertEqual(put_response.status_code, 401, put_response.content) #UNAUTHORIZED #test authenticate rpc_response = client.rpc('authenticate', email=self.user_post_data['email'], password=self.user_post_data['password']) self.assertEqual(200, rpc_response.status_code, rpc_response.content) #test PUT put_data = self.user_post_data put_data['first_name'] = "darth" put_response = client.put(userprofile_dict['resource_uri'], put_data) self.assertEqual(put_response.status_code, 204, put_response.content) #test PATCH patch_data = dict(put_data) patch_response = client.patch(userprofile_dict['resource_uri'], {'last_name': 'vader'}) self.assertEqual(patch_response.status_code, 202, patch_response.content) #test PATCH to superuser (not allowed) patch_data = {'is_superuser': True, 'is_staff': True} patch_response = client.patch(userprofile_dict['resource_uri'], patch_data) user_id = int(userprofile_dict['resource_uri'].split('/')[-2]) user = User.objects.get(id=user_id) self.assertFalse(user.is_superuser, "Allowed user to made himself superuser!") self.assertFalse(user.is_staff, "Allowed user to made himself staff!") #test PATCH to facebook_id (not allowed) patch_data = {'facebook_id': 12345678} patch_response = client.patch(userprofile_dict['resource_uri'], patch_data) user_id = int(userprofile_dict['resource_uri'].split('/')[-2]) user = User.objects.get(id=user_id) profile = UserProfile.get(user) self.assertNotEqual( 12345678, profile.facebook_id, "Allowed user to change his own facebook_id by POST/PUT!") #test matching GET get_response = client.get(userprofile_dict['resource_uri'], parse='json') userprofile_dict = get_response.data expected_data = dict(put_data) del expected_data['password'] expected_data['last_name'] = 'vader' self.assertEqual(get_response.status_code, 200, get_response.content) self.assertDictContainsSubset(expected_data, userprofile_dict)
def test_resource(self): client = self.client #test POST post_response = client.post(self.users_list_url, self.user_post_data) self.assertEqual(post_response.status_code, 201, post_response.content) #test matching GET get_response = client.get(self.users_list_url, parse='json') self.assertEqual(get_response.status_code, 200, get_response.content) userprofile_dict = get_response.data['objects'][0] userprofile_keys = userprofile_dict.keys() self.assertTrue('email' in userprofile_keys) self.assertTrue('facebook_id' in userprofile_keys) #test attempt unauthorized put put_data = dict(self.user_post_data) put_data['first_name'] = "darth" put_response = client.put(userprofile_dict['resource_uri'],put_data) self.assertEqual(put_response.status_code, 401, put_response.content) #UNAUTHORIZED #test authenticate rpc_response = client.rpc('authenticate', email=self.user_post_data['email'], password=self.user_post_data['password']) self.assertEqual(200,rpc_response.status_code, rpc_response.content) #test PUT put_data = self.user_post_data put_data['first_name'] = "darth" put_response = client.put(userprofile_dict['resource_uri'], put_data) self.assertEqual(put_response.status_code, 204, put_response.content) #test PATCH patch_data = dict(put_data) patch_response = client.patch(userprofile_dict['resource_uri'], {'last_name':'vader'}) self.assertEqual(patch_response.status_code, 202, patch_response.content) #test PATCH to superuser (not allowed) patch_data = {'is_superuser': True, 'is_staff' : True} patch_response = client.patch(userprofile_dict['resource_uri'], patch_data) user_id = int(userprofile_dict['resource_uri'].split('/')[-2]) user = User.objects.get(id=user_id) self.assertFalse(user.is_superuser,"Allowed user to made himself superuser!") self.assertFalse(user.is_staff,"Allowed user to made himself staff!") #test PATCH to facebook_id (not allowed) patch_data = {'facebook_id' : 12345678} patch_response = client.patch(userprofile_dict['resource_uri'], patch_data) user_id = int(userprofile_dict['resource_uri'].split('/')[-2]) user = User.objects.get(id=user_id) profile = UserProfile.get(user) self.assertNotEqual(12345678,profile.facebook_id,"Allowed user to change his own facebook_id by POST/PUT!") #test matching GET get_response = client.get(userprofile_dict['resource_uri'], parse='json') userprofile_dict = get_response.data expected_data = dict(put_data) del expected_data['password'] expected_data['last_name'] = 'vader' self.assertEqual(get_response.status_code, 200, get_response.content) self.assertDictContainsSubset(expected_data, userprofile_dict)
def test_get(self): user = User.objects.create_user(username="******", email="*****@*****.**", password="******") user.save() profile = UserProfile.get(user) self.assertEqual('test1', profile.username)