示例#1
0
文件: views.py 项目: egorsmth/hive
def create_user(user_data):
    user, created = User.objects.get_or_create(username=user_data['username'],
                                               email=user_data['email'])
    if created:
        user.set_password(user_data['password1'])
        user.save()
    profile = Profile(user=user, avatar='system/default_avatar.png')
    profile.save()
    return user
示例#2
0
 def post(self, request):
     serializer = UserSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     user = serializer.save()
     token, created = Token.objects.get_or_create(user=user)
     profile = Profile(email=user.email, user=user)
     profile.save()
     return Response({
         'token': token.key,
     }, status=status.HTTP_201_CREATED)
示例#3
0
def login_view(request):
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save()
        
        profile = Profile()
        profile.user = user
        profile.save()
        return redirect('game-home')
    return render(request, 'game/login.html', {'form': form})
示例#4
0
def create_profile_when_join(backend, user, response, *args, **kwargs):
    if backend.name == 'facebook':
        if not hasattr(user, 'profile'):
            profile = Profile(user_id=user.id,
                              photo='http://graph.facebook.com/{0}/picture?type=large'.format(response.get('id')),
                              level=10)
            profile.save()
            user.profile = profile

    return {'profile': user.profile}
    def handle(self, *args, **options):
        os.system("python manage.py makemigrations")
        os.system("python manage.py migrate")
        os.system("python manage.py loaddata fixtures/site_fixtures.json")

        user_item = User.objects.create_user(
            'FirstUserTestStudent',
            '*****@*****.**', 'asdf123!')

        user_item2 = User.objects.create_user(
            'SecondUserTestLibrarian',
            '*****@*****.**',
            'asdf123!',
            is_staff=True)

        profile_item = Profile(user=user_item, is_student=True)
        profile_item2 = Profile(user=user_item2, is_librarian=True)

        profile_item2.save()
        user_item2.save()
        profile_item.save()
        user_item.save()

        superuser_item = User.objects.create_superuser(
            'ThirdUserAdmin', '*****@*****.**',
            'asdf123!')
        superuser_item_profile = Profile.objects.create(user=superuser_item)
        superuser_item.save()
        superuser_item_profile.save()

        os.system(
            "python manage.py dumpdata --indent 2 --exclude=contenttypes --exclude=auth.permission > fixtures/test_db.json"
        )
示例#6
0
 def get(self, request):
     is_completed = False
     try:
         profile = Profile.objects.get(user=request.user)
     except:
         profile = Profile(user=request.user, email=request.user.email)
         profile.save()
     if profile.name != None and profile.email != None and profile.fb != None and profile.bio != None and profile.city != None:
         is_completed = True
     data = ProfileSerializer(profile).data
     return Response({
         'username': request.user.username,
         'id': request.user.id,
         'profile': data,
         'is_completed': is_completed
     }, status=status.HTTP_200_OK)
示例#7
0
def user_signup(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save(
                commit=False)  # create, but don't save the new user instance
            new_user.is_active = False
            new_user.save()
            profile = Profile(user=new_user,
                              first_name=request.POST.get('first_name'),
                              last_name=request.POST.get('last_name'))
            profile.save()

            #send activation email
            current_site = get_current_site(request)
            mail_subject = 'Activate Your Dimity Account'
            message = render_to_string(
                'auth_user/account_active_email.html',
                {
                    'user': new_user,
                    'domain': current_site.domain,
                    #In Django 2.0 you should call decode() after base64 encoding the uid, to convert it to a string
                    'uid': urlsafe_base64_encode(force_bytes(
                        new_user.id)).decode(),
                    'token': account_activation_token.make_token(new_user),
                })
            #print(urlsafe_base64_encode(force_bytes(new_user.id)) )
            #print(force_bytes(new_user.id))
            #print( urlsafe_base64_decode(urlsafe_base64_encode(force_bytes(new_user.id))).decode() )
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()

            context = {
                'check_email': 'Please check your mail to activate',
                'signup_form': UserRegistrationForm()
            }
            return render(request, 'auth_user/signup.html', context)
        else:
            context = {'signup_form': form}
    else:
        form = UserRegistrationForm()
        context = {'signup_form': form}
    return render(request, 'auth_user/signup.html', context)
示例#8
0
def create_user(username: str, email: str, is_librarian=False) -> User:
    """
    Creating user

    :param username: str
    :param email: str
    :returns: User
    """

    student_different = User.objects.create(username=username,
                                            email=email,
                                            password='******',
                                            is_staff=is_librarian)
    student_different_profile = Profile(user=student_different,
                                        is_student=(not is_librarian),
                                        is_librarian=is_librarian)
    student_different_profile.save()
    student_different.save()

    return student_different
示例#9
0
    def save(self, request: HttpRequest) -> User:
        """
        Saving new user

        :param request: HttpRequest
        """

        invite_key = self.cleaned_data.get('invite_key')
        first_name = self.cleaned_data.get('first_name')
        last_name = self.cleaned_data.get('last_name')

        user = super().save(request)

        user.first_name = first_name
        user.last_name = last_name
        user.save()

        profile = Profile(user=user)

        if invite_key == settings.LIBRARIAN_KEY:
            profile.is_librarian = True
            user.is_staff = True
            user.save()
        else:
            profile.is_student = True

        profile.save()
        return user
示例#10
0
    def handle(self, *args, **kwargs):
        """
        Django requires this method
        """
        users_without_profile = [
            user for user in User.objects.all()
            if not Profile.objects.filter(user=user).exists()
        ]
        u_length = len(users_without_profile)

        print('Users without profile: {}\n\n'.format(u_length))

        for user in users_without_profile:
            profile_item = Profile(
                user=user,
                custom_url=user.username,
            )

            profile_item.save()

            print('{}/{}'.format(u_length - 1, u_length))
            u_length -= 1
示例#11
0
 def create(self, validated_data):
     user = self._get_request().user
     if hasattr(user, 'profile'):
         raise serializers.ValidationError(
             {"error": _("This User has a profile!")})
     profile = Profile(user=user)
     fullname = validated_data.get('fullname', False)
     if fullname:
         fullname = fullname.split(' ')
         profile.user.first_name = fullname.pop(0)
         profile.user.last_name = " ".join(el for el in fullname)
         profile.user.save()
     return profile
示例#12
0
def submit_files(request):
    if request.method == 'POST':
        email = request.POST.get('email', '')
        profile = Profile()
        profile.email = email
        profile.files_num = len(request.FILES.getlist('files'))
        profile.finished_num = 0
        profile.save()
        ops_lm = []
        ops_dep = []
        text_models_lm = []
        text_models_dep = []
        # op_group = group([check_text_lm.s().set(queue="MC_lm"), check_text_dep_full.s().set(queue="MC_dep")])

        for file in request.FILES.getlist('files'):
            if not file.name.endswith(".tex") and not file.name.endswith(
                    ".txt"):
                continue
            # text_file_lm = TextFile()
            # text_file_lm.file_name = file.name
            # text_file_lm.file = file
            # text_file_lm.profile = profile
            # text_file_lm.ip = request.META.get("REMOTE_ADDR", "unknown")
            # text_file_lm.model_type = 0
            # text_file_lm.save()
            # text_models_lm.append(text_file_lm.id)

            text_file_dep = TextFile()
            text_file_dep.file_name = file.name
            text_file_dep.file = file
            text_file_dep.profile = profile
            text_file_dep.ip = request.META.get("REMOTE_ADDR", "unknown")
            text_file_dep.model_type = 1
            text_file_dep.save()
            text_models_dep.append(text_file_dep.id)

            op1 = preprocess.s(text_file_dep.file.path).set(queue="MC_util")
            # op2 = check_text_lm.s().set(queue="MC_lm")
            op3 = check_text_dep_full.s({}, 0).set(queue="MC_dep")
            # op_lm = (op1 | op2)
            op_dep = (op1 | op3)
            # ops_lm.append(op_lm)
            ops_dep.append(op_dep)
        if len(ops_dep) == 0:
            return render(request, "finish.html")
        # ops_lm_op = (group(ops_lm) | collect_result_lm.s(email, text_models_lm).set(queue="MC_util"))
        ops_dep_op = (group(ops_dep) | collect_result_dep.s(
            profile.id, text_models_dep).set(queue="MC_util"))
        # ops_lm_op.delay()
        ops_dep_op.delay()

        # print(profile.rawfile_set.all())

    return render(request, "finish.html")
示例#13
0
def nick_view(request):
	
	profiles = Profile.objects.all()
	for p in profiles:
		if request.user.id == p.user.id:
			
			return redirect('game-number')
	form = LoginForm(request.POST or None)
	if form.is_valid():
		profile = Profile()
		profile.name = form.cleaned_data['name']
		profile.user = request.user
		profile.save()
		return redirect('game-number')
	return render(request,'game/nick.html', context={'form':form})
示例#14
0
def api_create_user_view(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        # 先存user
        user_serializer = UserSerializer(data=data)
        try:
            with transaction.atomic():
                if user_serializer.is_valid():
                    new_user = user_serializer.save()
                    new_user.set_password(data.get('password'))
                    new_user.save()
                else:
                    return Response(user_serializer.errors,
                                    status=status.HTTP_400_BAD_REQUEST)

                # 再存profile
                if new_user is not None:
                    profile = Profile(user=new_user)
                    profile_serializer = ProfileSerializer(data=data,
                                                           instance=profile)
                    if profile_serializer.is_valid():
                        profile_serializer.save()
                    else:
                        new_user.delete()  # 驗證失敗時,把已經儲存的user刪掉
                        return Response(profile_serializer.errors,
                                        status=status.HTTP_400_BAD_REQUEST)
        except Exception as err:
            logging.error(err)
            return Response({'response': 'DB safe failed.'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        token = Token.objects.get(user=new_user).key
        message = {
            'user': user_serializer.data,
            'profile': profile_serializer.data,
            'token': token
        }
        return Response(message, status=status.HTTP_201_CREATED)
示例#15
0
def get(request):
    to_template = {}
    if request.user.is_authenticated:
        # Профайл пользователя
        try:
            profile = Profile.objects.get(user=request.user)
        except Profile.DoesNotExist:
            profile = Profile(user=request.user)
            profile.save()

        to_template['profile'] = {
            'username': profile.user.username,
            'email': profile.user.email
        }

        if profile.avatar:
            to_template['profile']['avatar'] = profile.avatar.url
        else:
            to_template['profile'][
                'avatar'] = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%2275%22%20height%3D%2275%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2075%2075%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_16571ccf1dd%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_16571ccf1dd%22%3E%3Crect%20width%3D%2275%22%20height%3D%2275%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2218.5546875%22%20y%3D%2242%22%3E75x75%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E'

        # Книги которые пользователь оценил
        ratings = StarRatings.objects.filter(user=request.user,
                                             book__isnull=False)
        to_template['books'] = []

        for rating in ratings:
            to_template['books'].append({
                'id':
                rating.book_id,
                'url':
                rating.book.get_absolute_url(),
                'title':
                rating.book.title,
                'authors':
                rating.book.get_link_authors(),
                'genres':
                rating.book.get_link_genres(),
                'rating':
                rating.book.rating,
                'userRating':
                rating.rating,
                'show_counter':
                rating.book.show_counter,
                'year':
                rating.book.year,
                'description':
                rating.book.description,
                'image':
                rating.book.get_image_preview()
            })

        # Посты пользователя
        posts = Publication.objects.filter(user=request.user)
        to_template['posts'] = []

        for post in posts:
            item = {
                'id': post.pk,
                'detailText': post.detail_text,
                'title': post.title,
                'showCounter': post.show_counter,
                'rating': post.rating,
                'dateUpdate': post.date_update,
                'url': post.get_absolute_url()
            }

            if post.image:
                item['image'] = post.image.url

            to_template['posts'].append(item)

        # Коллекции пользователя
        collections = Collection.objects.filter(user=request.user)
        to_template['collections'] = []

        for collection in collections:
            item = {
                'id': collection.pk,
                'text': collection.text,
                'title': collection.title,
                'showCounter': collection.show_counter,
                'rating': collection.rating,
                'dateUpdate': collection.date_update,
                'books': collection.book.all().count(),
                'url': collection.get_absolute_url()
            }

            if collection.image:
                item['image'] = collection.image.url

            to_template['collections'].append(item)

    return JsonResponse(to_template)
示例#16
0
 def get(self, request, hashed_code, format=None):
     '''
     function to handle GET request 
         verifies email and stores user in DB
     '''
     try:
         decoded_hashed_code = hashed_code.replace('__', '.')
         if not is_token_valid(decoded_hashed_code, 1440):
             return Response({'message': 'link expired'},
                             status=status.HTTP_410_GONE)
         user_data = jwt.decode(decoded_hashed_code.encode(),
                                SECRET_FOR_JWT,
                                algorithms=['HS256'])
         already_exists = User.objects.filter(
             email=user_data['email']).first()
         if already_exists:
             return Response({'message': 'already exists'},
                             status=status.HTTP_409_CONFLICT)
         password_hash = user_data['password_hash']
         # Obtain mesibo access token
         data = {
             "op": "useradd",
             "token": MESIBO_APPTOKEN,
             "addr": user_data['email'],
             "appid": MESIBO_APP_ID
         }
     except Exception as e:
         logger.error('Error in Verify GET is ', exc_info=1)
         return Response({'message': 'data error'},
                         status=status.HTTP_400_BAD_REQUEST)
     try:
         res = requests.post('https://api.mesibo.com/api.php', data=data)
     except Exception as e:
         logger.error('Error in Verify GET is ', exc_info=1)
         return Response({'message': 'mesibo failure'},
                         status=status.HTTP_503_SERVICE_UNAVAILABLE)
     mesibo_uid = res.json()['user']['uid']
     mesibo_token = res.json()['user']['token']
     try:
         user = User(name=user_data['name'],
                     email=user_data['email'],
                     password_hash=password_hash,
                     insti_email=user_data['insti_email'],
                     mesibo_details=MesiboUser(uid=mesibo_uid,
                                               access_token=mesibo_token),
                     profile=Profile())
         user.save()
     except Exception as e:
         logger.error('Error in Verify GET is ', exc_info=1)
         return Response({'message': 'db failure'},
                         status=status.HTTP_500_INTERNAL_SERVER_ERROR)
     try:
         subscriber_data = {
             "first_name": user_data['name'],
             "email": user_data['email']
         }
         content = {
             "list_ids": ["97cf46e3-e52f-4a9f-b43f-42f5edc02632"],
             "contacts": [subscriber_data]
         }
         headers = {
             "Authorization": "Bearer {}".format(SENDGRID_API_KEY),
             "Content-Type": "application/json"
         }
         r = requests.put('https://api.sendgrid.com/v3/marketing/contacts',
                          json=content,
                          headers=headers)
         return Response({'message': 'success'},
                         status=status.HTTP_201_CREATED)
     except Exception as e:
         logger.error('Error in Verify POST is ', exc_info=1)
         return Response({'message': 'not subscribed'},
                         status=status.HTTP_201_CREATED)
示例#17
0
def create_profile(sender, instance, created, **kwargs):
    if created:
        profile = Profile(user=instance)
        profile.save()
示例#18
0
        #mime type should be application/json    
        values = None
        
        try:
            values = json.loads(request.POST.keys()[0])
        except ValueError, err:
            logger.warning("The json received via POST to profile was not valid: %s" %request.POST.keys()[0])
            return HttpResponseBadRequest("JSON error: " + str(err.args))
        except IndexError:
            return HttpResponseBadRequest(_("POST data was empty so could not save the profile"))

        current_profile = None
        try:
            current_profile = Profile.objects.filter(user__exact = request.user).latest('create_time')
            
            current_profile.update(json.dumps(values))
            
            
        except ObjectDoesNotExist:
            logger.info("The user %s does not have a profile" % request.user.username)

            new_profile_value = Profile(user = request.user,
                                       json_string = json.dumps(values))
            new_profile_value.save()

            logger.info("The profile %s for user %s was saved successfully" % (values, request.user.username))

        return HttpResponse(_("The profile has been saved"))
        
    return HttpResponseBadRequest(_("This function only support GET and POST methods"))