Example #1
0
def show_conatct_as_owner(request, message=None):
    try:
        Sitter.objects.get(user_id=get_user(request))
        is_sitter = True
    except:
        is_sitter = False

    print("메세지", message)

    contacts = Contact.objects.filter(owner=get_user(request))

    contact_info = []
    for contact in contacts:
        temp = contact.__dict__
        temp['photo'] = myModule.get_userimg(contact.sitter)
        temp['sitter'] = contact.sitter
        temp['score'] = myModule.get_sitter_score(contact.sitter)
        contact_info.append(temp)

    return render(
        request, 'contact/contact_list.html', {
            'contacts': contact_info,
            'owner_contact': True,
            'is_sitter': is_sitter,
            'message': message,
        })
Example #2
0
def update_img(request):
    info = UserImage.objects.get(user=get_user(request))
    form = ImageCreateForm(request.POST or None, instance=info)

    if request.method == 'POST' and form.is_valid():
        image = form.save(commit=False)
        image.user = get_user(request)
        image.save()
        return HttpResponseRedirect("/accounts")

    return render(request, 'accounts/user_manage.html', {
        'form': form,
    })
Example #3
0
def edit_sitter(request):
    info = Sitter.objects.get(user_id = get_user(request))
    form = SitterCreateForm(request.POST or None, instance = info)

    if request.method == 'POST' and form.is_valid():
        sitter = form.save(commit=False)
        sitter.user_id = get_user(request)
        sitter.save()
        return HttpResponseRedirect("/accounts")

    return render(request, 'accounts/sitter_manage.html', {
        'form':form,
        'is_add':False,
Example #4
0
def add_bookmark(request, post_id, move):
    try:
        bookmark = Bookmark.objects.create(
            user=get_user(request), post=Post.objects.get(id=int(post_id)))
    except IntegrityError:  #이미 등록된 찜글일 때
        Bookmark.objects.get(user=get_user(request),
                             post=Post.objects.get(id=int(post_id))).delete()
    except:  #로그인하지 않은 유저일때
        return HttpResponseRedirect("/accounts")

    if move == "True":
        return HttpResponseRedirect("/bookmark")
    else:
        return HttpResponseRedirect("/posting/id={}".format(post_id))
Example #5
0
    def get_jwt_user(request):
        user = get_user(request)
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            jwt_value = jwt_authentication.get_jwt_value(request)
            import jwt
            try:
                payload = jwt_decode_handler(jwt_value)
            except jwt.ExpiredSignature:
                print("Signature expired.")
                msg = {
                    'jwtResponse': 'Signature has expired.'
                }
                return msg
            except jwt.DecodeError:
                print('Error decoding signature.')
                msg = {
                    'jwtResponse': 'Error decoding signature.'
                }
                return msg
            except jwt.InvalidTokenError:
                print("invalid token error")
                return exceptions.AuthenticationFailed()

            user = jwt_authentication.authenticate_credentials(payload)

            user, jwt = jwt_authentication.authenticate(request)
        return user
Example #6
0
    def __init__(self, path, session_key):
        from django.contrib.auth.middleware import get_user

        self.session_key = session_key

        self.path = path
        self.user = SimpleLazyObject(lambda: get_user(self))
Example #7
0
def get_user_jwt_or_oauth2(request):
    user = get_user(request)

    if user.is_authenticated():
        return user

    # JWT
    try:
        from rest_framework_jwt.authentication import JSONWebTokenAuthentication

        try:
            user_jwt = JSONWebTokenAuthentication().authenticate(
                Request(request))
            if user_jwt is not None:
                return user_jwt[0]
        except:
            pass
    except ModuleNotFoundError:
        pass

    # OAuth2
    try:
        from oauth2_provider.contrib.rest_framework import OAuth2Authentication

        try:
            user_o2 = OAuth2Authentication().authenticate(request)
            if user_o2 is not None:
                return user_o2[0]
        except:
            pass
    except ModuleNotFoundError:
        pass

    return user
    def as_request(self):
        assert self.request_data, 'Could not construct an empty TestCase object'
        request = http.HttpRequest()
        data = self.request_data_dict
        request.path = data['path']
        request.method = data['method']
        request.path_info = data['path_info']
        request._body = data['body']
        request.META = data['headers']
        request._encoding = data['encoding']
        request._stream = StringIO()
        request._read_started = False
        request._post_parse_error = False
        request.resolver_match = None

        request._load_post_and_files()
        query_string = '%s&%s=1' % (data['query_string'], TEST_REQUEST_PARAM)
        request.GET = http.QueryDict(query_string, encoding=request.encoding)
        request.POST = getattr(request, '_post')
        request.FILES = getattr(request, '_files')
        request.COOKIES = http.parse_cookie(
            request.META.get('HTTP_COOKIE', b''))
        request.REQUEST = datastructures.MergeDict(request.POST, request.GET)

        # extra attributes added by middlewares
        from django.contrib.auth.middleware import get_user
        engine = import_module(settings.SESSION_ENGINE)
        request.session = engine.SessionStore(
            request.COOKIES.get(settings.SESSION_COOKIE_NAME, None))
        request.user = SimpleLazyObject(lambda: get_user(request))
        return request
Example #9
0
def blog(request, project_id):
    project = get_object_or_404(Project, id=project_id)
    
    if not get_user(request).is_authenticated and not project.is_public:
        return redirect_to_login(request.get_full_path())    
      
    return render(request, 'PhotoBlog/blog.html', {'project': project})
Example #10
0
    def get(self, request, *args, **kwargs):
        user = get_user(request)

        if authenticate_user_credentials(user):
            return Response({}, status=status.HTTP_200_OK)

        return Response({}, status=status.HTTP_403_FORBIDDEN)
def _get_user_from_jwt(request, view_func):
    user = get_user(request)
    if user.is_authenticated:
        return user

    try:
        jwt_authentication_class = _get_jwt_authentication_class(view_func)
        if jwt_authentication_class:
            user_jwt = jwt_authentication_class().authenticate(
                Request(request))
            if user_jwt is not None:
                return user_jwt[0]
            else:
                log.warning(
                    'Jwt Authentication failed and request.user could not be set.'
                )
        else:
            log.warning(
                'Jwt Authentication expected, but view %s is not using a JwtAuthentication class.',
                view_func)
    except Exception:  # pylint: disable=broad-except
        log.exception(
            'Unknown error attempting to complete Jwt Authentication.'
        )  # pragma: no cover

    return user
Example #12
0
def showPost(request, post_id):
    post_obj = Post.objects.get(id = int(post_id))
    form = ContactForm(request.POST or None, request.FILES or None, post_id = post_obj)

    if request.method == 'POST' and form.is_valid():
        return create_contact(request, form, post_obj)

    # GET or invalid form
    sitter_obj = post_obj.author
    post = post_obj.__dict__
    post['species_of_animal'] = Species.objects.all().filter(post = post_id)
    post['number_of_animal'] = myModule.get_number_of_pet(sitter_obj.user_id)
    try:
        Bookmark.objects.get(user = get_user(request), post = post_obj)
        post['marked'] = True
    except:
        post['marked'] = False

    sitter = sitter_obj.__dict__
    sitter['name'] = str(sitter_obj)
    sitter['score'] = myModule.get_sitter_score(sitter_obj)
    sitter['photo'] = myModule.get_userimg(sitter_obj)

    return render(request, 'posting/post_detail.html', {
        'post' : post, 
        'sitter':sitter, 
        'form':form,
    } )
Example #13
0
def show_list(request, post_objects, is_show_post=True, message = None):
    form = search_form(request.POST or None, request.FILES or None)
    
    try : # 검색자가 시터인지 아닌지 파악 - 글쓰기 버튼 활성화
        Sitter.objects.get(user_id = get_user(request))
        is_sitter = True
    except: #(TypeError, AttributeError, ObjectDoesNotExist):
        is_sitter = False
    
    posts = []
    for post_obj in post_objects:
        sitter = post_obj.author
        
        post = post_obj.__dict__
        post['author'] = sitter.__dict__
        post['author']['name'] = str(sitter)
        post['author']['photo'] = myModule.get_userimg(sitter)
        post['author']['score'] = myModule.get_sitter_score(sitter)
        post['author']['score'] = myModule.get_sitter_score(sitter)
        post['author']['number_of_animal'] = myModule.get_number_of_pet(sitter)
        posts.append(post)
    
    return render(request, 'posting/post_list.html', {
        'posts': posts,
        'form': form,
        'is_sitter' : is_sitter,
        'is_show_post' : is_show_post,
        'message' : message,
        
    } )
    def resolve(self, next, root, info, **kwargs):
        context = info.context
        token_argument = get_token_argument(context, **kwargs)

        if jwt_settings.JWT_ALLOW_ARGUMENT and token_argument is None:
            user = self.cached_authentication.parent(info.path)

            if user is not None:
                context.user = user

            elif hasattr(context, 'user'):
                if hasattr(context, 'session'):
                    context.user = get_user(context)
                else:
                    context.user = AnonymousUser()

        if ((_authenticate(context) or token_argument is not None)
                and self.authenticate_context(info, **kwargs)):

            user = authenticate(request=context, **kwargs)

            if user is not None:
                context.user = user

                if jwt_settings.JWT_ALLOW_ARGUMENT:
                    self.cached_authentication.insert(info.path, user)

        return next(root, info, **kwargs)
Example #15
0
 def retrieve(self, request, *args, **kwargs):
     user1 = get_user(self.request)
     user2_id = self.kwargs['pk']  # it's user's pk really
     instance = Room.objects.filter(members=user1).filter(
         members__id=user2_id).first()
     serializer = self.get_serializer(instance)
     return Response(serializer.data)
Example #16
0
    def __call__(self, request):
        if not request.user.is_authenticated:
            request.user = SimpleLazyObject(
                lambda: self.get_user(request) or get_user(request)
            )

        return self.get_response(request)
Example #17
0
 def process_request(self, request):
     """Process request handler"""
     try:
         from django.contrib.auth.middleware import get_user
         request.user = get_user(request)
     except:
         pass
Example #18
0
def show_conatct_as_sitter(request):
    contacts = Contact.objects.fiter(sitter = get_user(request))
    contact_info = []
    for contact in contacts:
        temp = {}
        temp['contact'] = contact
        temp['image'] = myModule.get_userimg_by_userobj(contact.owner)
        contact_info.append(temp)
Example #19
0
 def get_jwt_user(request):
     user = get_user(request)
     if user.is_authenticated:
         return user
     jwt_authentication = JSONWebTokenAuthentication()
     if jwt_authentication.get_jwt_value(request):
         user, jwt = jwt_authentication.authenticate(request)
     return user
Example #20
0
def show_conatct_as_sitter(request):
    contacts = Contact.objects.fiter(sitter=get_user(request))
    contact_info = []
    for contact in contacts:
        temp = {}
        temp['contact'] = contact
        contact_info.append(temp)
        contact_info.append(temp)
Example #21
0
def send_miss_you(request, contact_id, message):
    contact = Contact.objects.get(id=int(contact_id))
    phone_number = contact.sitter.phoneNumber
    message = "계약자 '{0}'님이 아이가 잘 있는지 궁금해 합니다. 사진을 보내주세요!".format(
        get_user(request))
    send_message(phone_number, message)

    return HttpResponseRedirect("/contact")
Example #22
0
 def process_request(self, request):
     if not hasattr(request, 'user') or not request.user.is_authenticated:
         auth_bearer = request.META.get('HTTP_AUTHORIZATION')
         if auth_bearer and 'token' in auth_bearer:
             token = auth_bearer.replace('token', '').strip()
             request.user = auth.authenticate(token=token)
         else:
             request.user = SimpleLazyObject(lambda: get_user(request))
 def process_request(self, request):
     assert hasattr(request, 'session')
     user = get_user(request)
     if user.is_authenticated is False:
         if request.META.get('HTTP_AUTHORIZATION', None):
             if len(request.META['HTTP_AUTHORIZATION'].split(" ")) > 1:
                 self.authenticate(
                     request.META['HTTP_AUTHORIZATION'].split(" ")[1])[0]
Example #24
0
 def process_request(self, request):
     assert hasattr(request, 'session'), (
                                             "The Django authentication middleware requires session middleware "
                                             "to be installed. Edit your MIDDLEWARE%s setting to insert "
                                             "'django.contrib.sessions.middleware.SessionMiddleware' before "
                                             "'django.contrib.auth.middleware.AuthenticationMiddleware'."
                                         ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")
     if request.path.startswith('/admin/'):
         request.user = SimpleLazyObject(lambda: get_user(request))
Example #25
0
def get_person(request):
    user = get_user(request)
    if user.is_anonymous:
        return None

    try:
        return user.person
    except (AttributeError, Person.DoesNotExist):
        return None
Example #26
0
def auth(request):
    """
    Renvoie des variables de contexte similaire à celles renvoyées par
    django.contrib.auth.context_processors.auth, mais en y rajoutant la
    possibilité de tester les permissions spécifiques à un objet.

    Pour cela, il faut tester si l'objet est "dans" la permission, par
    exemple :

        {% if obj in perms.app.view_model %}
    """

    return {
        "user": SimpleLazyObject(lambda: get_user(request)),
        "perms": SimpleLazyObject(lambda: PermWrapper(get_user(request))),
        "person": SimpleLazyObject(lambda: get_person(request)),
        "gender": SimpleLazyObject(lambda: get_person(request).gender),
    }
Example #27
0
 def _process_request(self, request):
     if "HTTP_X_GROUPS" in request.META:
         groups = request.META["HTTP_X_GROUPS"] or None
         existing_groups = request.session.get("usergroups")
         if groups != existing_groups:
             # user group is changed.
             request.user = SimpleLazyUser(lambda: get_user(request),
                                           request, groups)
             return
     original_process_request(self, request)
Example #28
0
def create_contact(form, post):
    if form.is_valid():
        contact = form.save(commit=False)
        contact.sitter = post.author
        contact.owner = get_user(request)
        contact.save()

        send_message(contact.sitter.phoneNumber,
                     "새로운 계약 요청이 들어왔습니다. 지금 확인해보세요.")
        return HttpResponseRedirect("/contact")
Example #29
0
def cancel_contact(request, contact_id):
    contact = Contact.objects.get(id=int(contact_id))
    contact.status = "cancel"
    contact.save()

    phone_number = contact.sitter.phoneNumber
    message = "게약자 '{0}'님이 예약을 취소했습니다".format(get_user(request))
    send_message(phone_number, message)

    return HttpResponseRedirect("/contact")
Example #30
0
    def get_jwt_user(request):
        user = get_user(request)

        # prevent the generation of Token for anonymous user
        if user.is_authenticated:
            return user
        jwt_authentication = JSONWebTokenAuthentication()
        if jwt_authentication.get_jwt_value(request):
            user, jwt = jwt_authentication.authenticate(request)
        return user
Example #31
0
def incident_form_func(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = incident_formForm(request.POST)
            if form.is_valid():
                obj = incident_form()
                user = get_user(request)
                obj.submitted_by = user.get_username()
                obj.aircraft_identification = form.cleaned_data[
                    'aircraft_identification']
                obj.type_of_incident = form.cleaned_data['type_of_incident']
                obj.date_of_incident = form.cleaned_data['date_of_incident']
                obj.time_of_incident = form.cleaned_data['time_of_incident']
                obj.pos = form.cleaned_data['pos']
                obj.head_and_route = form.cleaned_data['heading_and_route']
                obj.true_airspeed = form.cleaned_data['true_airspeed']
                obj.speed_measured = form.cleaned_data['speed_measured']
                obj.air_climb = form.cleaned_data['air_climb']
                obj.air_bank = form.cleaned_data['air_bank']
                obj.air_dir = form.cleaned_data['air_dir']
                obj.restr_visib = form.cleaned_data.get('restr_visib')
                obj.air_light = form.cleaned_data.get('air_light')
                obj.traffic_advice = form.cleaned_data['traffic_advice']
                obj.traffic_info = form.cleaned_data['traffic_info']
                obj.ACAS = form.cleaned_data['ACAS']
                obj.radar = form.cleaned_data['radar']
                obj.other_aircraft = form.cleaned_data['other_aircraft']
                obj.avoid_action = form.cleaned_data['avoid_action']
                obj.type_of_flight_plan = form.cleaned_data[
                    'type_of_flight_plan']
                obj.type_and_call_sign = form.cleaned_data[
                    'type_and_call_sign']
                obj.other_available_details = form.cleaned_data[
                    'other_available_details']
                obj.aircraft_reg = form.cleaned_data['aircraft_reg']
                obj.aircraft_type = form.cleaned_data['aircraft_type']
                obj.operator = form.cleaned_data['operator']
                obj.aero_depart = form.cleaned_data['aero_depart']
                obj.aero_first_landing = form.cleaned_data[
                    'aero_first_landing']
                obj.destination = form.cleaned_data['destination']
                obj.operation_department = form.cleaned_data.get(
                    'operation_department')
                obj.ATC_mark = form.cleaned_data.get('ATC_mark')
                obj.DGCA_mark = form.cleaned_data.get('DGCA_mark')
                obj.save()
                return render(request, 'useraccount/form_submitted.html')
            # return HttpResponse("Submit your Incident here !")
        else:
            form = incident_formForm()

        return render(request, 'useraccount/incident_form.html',
                      {'form': form})
    return HttpResponse("Not Logged In")
Example #32
0
def get_user_jwt(request):
    user = get_user(request)
    if user.is_authenticated():
        return user
    try:
        user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
        if user_jwt is not None:
            return user_jwt[0]
    except:
        pass
    return user
Example #33
0
def get_user_jwt(request):
    user = get_user(request)
    if user.is_authenticated():
        return user
    try:
        user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
        if user_jwt is not None:
            return user_jwt[0]
    except:
        pass
    return user
Example #34
0
    def __call__(self, request):
        from django.utils.functional import SimpleLazyObject
        from django.contrib.auth.middleware import get_user

        user = get_user(request)

        if not user.is_authenticated():
            request.userprofile = SimpleLazyObject(lambda: self.get_user(request))
        else:
            request.userprofile = None

        return self.get_response(request)
Example #35
0
def get_user_jwt(request):
    user = get_user(request)
    if user.is_authenticated():
        return user, None
    try:
        user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
        print "user_jwt: ", user_jwt
        if user_jwt is not None:
            return user_jwt[0], user_jwt[1]
        else:
            return None, None
    except Exception, e:
        print "exception", e
        pass
Example #36
0
    def get_user_jwt(self, request):
        from rest_framework.request import Request
        from rest_framework.exceptions import AuthenticationFailed
        from django.utils.functional import SimpleLazyObject
        from django.contrib.auth.middleware import get_user
        from rest_framework_jwt.authentication import JSONWebTokenAuthentication

        user = get_user(request)
        if user.is_authenticated():
            return user
        try:
            user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
            if user_jwt is not None:
                return user_jwt[0]
        except AuthenticationFailed:
            pass
        return user
 def stub(cls, **kwargs):
     method = kwargs.pop('method')
     path = kwargs.pop('path', '/test/')
     data = kwargs.pop('data', {})
     session = kwargs.pop('session', SessionStore())
     user = kwargs.pop('user', None)
     auth_backend = kwargs.pop('backend',
         'django.contrib.auth.backends.ModelBackend')
     request = method(path, data, **kwargs)
     request.session = session
     if user:
         request.session[SESSION_KEY] = user.id
         request.session[BACKEND_SESSION_KEY] = auth_backend
         request.user = SimpleLazyObject(lambda: get_user(request))
     else:
         request.user = AnonymousUser()
     request._messages = BaseStorage(request)
     return request
Example #38
0
def get_user_jwt(request):
    # log.debug("Authentication Middleware: get_user_jwt")
    user = get_user(request)
    # log.debug("Authentication Middleware: get_user_jwt :: user = "******"Authentication Middleware: User is authenticated : returning ::" + str(user))
        return user
    try:
        user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
        # log.debug("Authentication Middleware: get_user_jwt :: user_jwt = " + str(user_jwt))
        if user_jwt is not None:
            # log.debug("Authentication Middleware: get_user_jwt :: user_jwt is not None")
            return user_jwt[0]
    except:
        pass

    # log.debug("Authentication Middleware: Reached end of get_user)jwt : returning ::" + str(user))
    return user
Example #39
0
def get_bloguser(request):
	_user = get_user(request)
	try:
		return Bloguser.objects.get(pk=_user.pk)
	except Bloguser.DoesNotExist:
		return _user
Example #40
0
def user_profile(request):
    if request.method == 'POST':
        user = get_user(request)
        # The user-form atribute in the request represents changes were made to
        # the user information
        if "user-form" in request.POST:
            form = UserForm(request.POST)
            # The form is evaluated and if valid its updated
            if form.is_valid():
                username = form.cleaned_data.get('username')
                email = form.cleaned_data.get('email')
                first_name = form.cleaned_data.get('first_name')
                last_name = form.cleaned_data.get('last_name')
                if username:
                    User.objects.filter(id=user.id).update(username=username)
                if email:
                    User.objects.filter(id=user.id).update(email=email)
                if first_name:
                    User.objects.filter(id=user.id).update(
                        first_name=first_name)
                if last_name:
                    User.objects.filter(id=user.id).update(last_name=last_name)
                # A message is added so the user knows his information was
                # updated
                messages.add_message(
                    request, messages.SUCCESS,
                    'Perfil actualizado correctamente.',
                    extra_tags={'user': '******'})
            # If there is an error with the inputs a message is added with the
            # errors
            else:
                for field in form:
                    for error in field.errors:
                        messages.add_message(request, messages.ERROR, error)
        # The profile-form atribute in the request represents changes were made
        # to the user profile
        elif "profile-form" in request.POST:
            form = UserProfileForm(request.POST)
            # The form is evaluated and if valid its updated
            if form.is_valid():
                birthday = form.cleaned_data.get('birthday')
                gender = form.cleaned_data.get('gender')
                height = form.cleaned_data.get('height')
                weight = form.cleaned_data.get('weight')
                elbow_diameter = form.cleaned_data.get('elbow_diameter')
                if birthday:
                    UserProfile.objects.filter(
                        user=user).update(birthday=birthday)
                if gender:
                    UserProfile.objects.filter(user=user).update(gender=gender)
                if height:
                    UserProfile.objects.filter(user=user).update(height=height)
                if weight:
                    UserProfile.objects.filter(user=user).update(weight=weight)
                if elbow_diameter:
                    UserProfile.objects.filter(user=user).update(
                        elbow_diameter=elbow_diameter)
                # A message is added so the user knows his profile was updated
                messages.add_message(
                    request, messages.SUCCESS,
                    'Perfil actualizado correctamente.',
                    extra_tags=('profile'))
            # If there is an error with the inputs a message is added with the
            # errors
            else:
                for field in form:
                    for error in field.errors:
                        messages.add_message(
                            request, messages.ERROR,
                            error,
                            extra_tags=('profile'))
        # User is redirected to the profile page
        return HttpResponseRedirect('/accounts/profile/')
    else:
        # The user profile is obtained and two empy forms for user information
        # and profile are created
        profile = request.user.get_profile()
        form_user = UserForm
        form_profile = UserProfileForm
        # Possible previous messages are collected, processed and added to the
        # context
        messages_temp = get_messages(request)
        profile_messages = False
        for message in messages_temp:
            if 'profile' in message.tags:
                profile_messages = True
        return render(
            request,
            'profile/profile.html',
            {
                'profile': profile,
                'form_profile': form_profile,
                'form_user': form_user,
                'profile_messages': profile_messages
            }
        )
Example #41
0
 def process_request(self, request):
     request.user = get_user(request)
Example #42
0
    def process_request(self, request):

        if 'HTTP_AUTHORIZATION' in request.META:
            request.user = SimpleLazyObject(lambda: get_api_user(request))
        else:
            request.user = SimpleLazyObject(lambda: get_user(request))