Beispiel #1
0
 def post(self, request, *args, **kwargs):
     """Handles logic and Returns response for `POST`
     requests to `/login`"""
     username = request.POST.get('username')
     password = request.POST.get('password')
     if not request.POST.get('remember_me', None):
         request.session.set_expiry(0)
     if '@' in username:
         kwargs = {'email': username}
     else:
         kwargs = {'username': username}
     try:
         user = User.objects.get(**kwargs)
         if user.check_password(password):
             user_backend = authenticate(
                 username=user.username,
                 password=password,
             )
             if not user_backend:
                 raise User.DoesNotExist()
             login(request, user_backend)
             return redirect(reverse('app.dashboard'))
         else:
             raise User.DoesNotExist()
     except (User.DoesNotExist, User.MultipleObjectsReturned):
         messages.error(request, 'Wrong username or password.')
         return redirect(reverse('app.index'))
Beispiel #2
0
    def _remove_django_user(username):
        # Get the user associated with the username, delete their apps, and
        # then delete the user
        try:
            user = User.objects.get(username=username)
            apps = App.objects.filter(user=user)
            for app in apps:
                app_id = app.app_id
                DataHubManager.remove_app(app_id=app_id)

            Collaborator.objects.filter(user=user).delete()
            user.delete()
        except User.DoesNotExist:
            user = None

        # Do the same thing for legacy users
        try:
            legacy_user = DataHubLegacyUser.objects.get(username=username)
            apps = App.objects.filter(legacy_user=legacy_user)
            for app in apps:
                app_id = app.app_id
                DataHubManager.remove_app(app_id=app_id)
            legacy_user.delete()
        except DataHubLegacyUser.DoesNotExist:
            legacy_user = None

        # Raise a not found exception if this didn't result in any deletions
        if not user and not legacy_user:
            raise User.DoesNotExist()
Beispiel #3
0
def signupView(request) : 
    if request.method == 'POST' : 
        try : 
            #   checking if the user already exists
            username = request.POST.get('username')
            email = request.POST.get('email')
            password = request.POST.get('password')

            if not is_valid_email(email) or not is_valid_username(username) :
                messages.error(request, 'Invalid username or email address')
                return redirect('/account/signup/')
            
            if User.objects.filter(username=username).exists() or User.objects.filter(email=email).exists() : 
                messages.error(request,'User already exists with those credentials')
                return redirect('/account/signup/')
            else :
                raise User.DoesNotExist()

        except User.DoesNotExist : 
            #   when the user doesnot exist we create a new user
            user = User.objects.create_user(username=username, email=email, password=password)
            profile = UserProfile(
                user=user,
                username=username,
                profile_pic = request.FILES.get('profile_pic', 'default.png'),
                bio = request.POST.get('bio')
            )
            profile.save()
            user.save()
            messages.success(request, 'Account succesfully created. Please login to continue.')
            return redirect('/account/login/')

    else : 
        # request method is GET
        return render(request, 'account/signup.html')
Beispiel #4
0
    def submit_group_completion(self, block_key, completion, users=None, user_ids=None):
        """
        Submit a completion for a group of users.

        Arguments:

            block_key (opaque_key.edx.keys.UsageKey): The block to submit completions for.
            completion (float): A value in the range [0.0, 1.0]
            users ([django.contrib.auth.models.User]): An optional iterable of Users that completed the block.
            user_ids ([int]): An optional iterable of ids of Users that completed the block.

        Returns a list of (BlockCompletion, bool) where the boolean indicates
        whether the given BlockCompletion was newly created.
        """
        if users is None:
            users = []
        if user_ids is None:
            user_ids = []
        more_users = User.objects.filter(id__in=user_ids)
        if len(more_users) < len(user_ids):
            found_ids = {u.id for u in more_users}
            not_found_ids = [pk for pk in user_ids if pk not in found_ids]
            raise User.DoesNotExist("User not found with id(s): {}".format(not_found_ids))
        users.extend(more_users)

        submitted = []
        for user in users:
            submitted.append(BlockCompletion.objects.submit_completion(
                user=user,
                block_key=block_key,
                completion=completion
            ))
        return submitted
    def testAcceptFromRealEndpoint(self):
        username = '******'
        request = RequestFactory().post('/login', {
            'username': username,
            'password': '******'
        })
        server = self.TestWebServer(self.Always200Handler)
        server.start()
        auth = HttpBasicEndpointAuth(endpoint=server.getUrl())
        # Stub out user object retrieval & creation
        mockUserDao = flexmock(User.objects)
        mockUserDao.should_receive('get').and_raise(User.DoesNotExist())
        mockUserDao.should_call('create_user').with_args(username, '')\
            .at_least.once
        # Ditto for group object retrieval
        group = Group.objects.create(name='test-group')
        group.save()
        mockGroupDao = flexmock(Group.objects)
        mockGroupDao.should_receive('get').with_args(name='test-group')\
            .and_return(group).at_least.once
        mockGroupDao.should_receive('get').with_args(name='unknown-group')\
            .and_raise(Group.DoesNotExist)

        result = auth.authenticate(request)
        server.stop()
        self._checkResult(result, username)
Beispiel #6
0
 def get_user_from_irc_nick(self, irc_nick):
     irc_nick = irc_nick.lstrip(":").lower()
     users = get_or_create_bugzilla_users(self.query_users(":" + irc_nick))
     for user in users:
         if user.username.lower() == irc_nick:
             return user
     raise User.DoesNotExist()
Beispiel #7
0
def join(request, username, groupname):
    """Add user to a group specified by name.

    :param str username: user name.
    :param str groupname: group name to add given user name.

    :raise PermissionDenied: if the request has no permission to add a user to
        a group.
    :raise Object.DoesNotExist: if user name or group name does not exist.

    Example::

        >>> User.join('username', 'groupname')
    """
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise User.DoesNotExist('User "%s" does not exist' % username)
    else:
        try:
            group = Group.objects.get(name=groupname)
        except Group.DoesNotExist:
            raise Group.DoesNotExist('Group "%s" does not exist' % groupname)
        else:
            user.groups.add(group)
Beispiel #8
0
 def authenticate(self, request, username=None, password=None):
     try:
         user = User.objects.get(email=username)
         if user.check_password(password):
             return user
         return None
     except User.DoesNotExist():
         return None
 def get_user_from_auth(request):
     try:
         user_id = request.auth.user_id
     except ValueError:
         raise ValueError("Invalid authentication token!")
     try:
         return User.objects.get(pk=user_id)
     except User.DoesNotExist:
         raise User.DoesNotExist("User for given id does not exists!")
 def fromUser(**kwargs):
     user = User.objects.get(**kwargs)
     if hasattr(user, 'trosnothuser'):
         result = user.trosnothuser
     elif user.username == 'autoadmin':
         # Special case: autoadmin is not allowed to actually play
         raise User.DoesNotExist('autoadmin is not allowed to play')
     else:
         result = TrosnothUser(user=user, nick=user.username)
         result.save()
     return result
Beispiel #11
0
def send_password_reset_email(email, request=None):
    form = PasswordResetForm({'email': email})
    if not form.is_valid():
        raise User.DoesNotExist(email)

    request = request or create_request_for_email()

    template_base = 'wagtailadmin/account/password_reset/'
    form.save(request=request,
              subject_template_name=template_base + 'email_subject.txt',
              email_template_name=template_base + 'email.txt',
              use_https=request.is_secure())
 def default_django_user(self):
     login_id = ""
     # first choice: web user login
     if self.web_account.login_id:
         login_id = self.web_account.login_id
     # second choice: latest registered commcare account
     elif self.commcare_accounts:
         login_id = _get_default(self.commcare_accounts).login_id
     else:
         raise User.DoesNotExist(
             "This couch user doesn't have a linked django login!")
     return django_user_from_couch_id(login_id)
 def testAllowOnSuccess(self):
     username = '******'
     request = RequestFactory().post('/login', { 'username': username,
                                                'password': '******'})
     # A "successful" mock OpenerDirector
     result = tempfile.TemporaryFile(mode='r')
     mockOpener = flexmock(urllib2.OpenerDirector(), open = result)
     # Stub out user object retrieval & creation
     mockUserDao = flexmock(User.objects)
     mockUserDao.should_receive('get').and_raise(User.DoesNotExist())
     mockUserDao.should_call('create_user').with_args(username, '')\
         .at_least.once
     auth = HttpBasicEndpointAuth(mockOpener,endpoint=self.mock_endpoint)
     self._checkResult(auth.authenticate(request),username)
Beispiel #14
0
    def test_backend_profile_exceptions(self, p_mock):
        # We have a legitimate profile, but for some reason the user_id is
        # phony.
        s = SessionBackend()
        session = Session.objects.get(pk='17f051c99f083244bf653d5798111216')

        p_mock.side_effect = User.DoesNotExist()
        eq_(None, s.authenticate(session))

        p_mock.side_effect = IntegrityError()
        eq_(None, s.authenticate(session))

        p_mock.side_effect = Exception()
        eq_(None, s.authenticate(session))
    def authenticate(self, request):
        username = request.GET.get('username')

        if username is None:
            return None

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist():
            raise AuthenticationFailed("username does't match")
        return (user, None)


#on web
#http://127.0.0.1:8000/studentapi/?username=piyush
Beispiel #16
0
def join(request, username, groupname):
    """
    Description: Add user to a group specified by name.

    Returns: None
    
    Raises: PermissionDenied
            Object.DoesNotExist

    Example:
    >>> User.join('username', 'groupname')
    """
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist, e:
        raise User.DoesNotExist('User "%s" does not exist' % username)
Beispiel #17
0
def GET_USER_BY_USERNAME(username):
    from django.contrib.auth.models import User
    #  from django_auth_ldap.backend import LDAPBackend

    for domain in ('@clemson.edu', '@g.clemson.edu', '@exchange.clemson.edu'):
        if username.lower().endswith(domain):
            username = username[:-len(domain)]
            break

    try:
        return User.objects.get(username=username)
    except User.DoesNotExist:
        #    backend = LDAPBackend()
        user = backend.populate_user(username)
        if user is None:
            raise User.DoesNotExist('%s not in LDAP or database' % username)
        return user
Beispiel #18
0
def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, User.DoesNotExist()):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        # profile.save()
        # registered = True
        login(request, user)

        return HttpResponse(
            'Thank you for your email confirmation. Now you can login your account.'
        )
        # return redirect('home')
    else:
        return HttpResponse('Activation link is invalid or Expired!')
Beispiel #19
0
def fse_username_validator(username):
    flag = True
    try:
        _ = User.objects.get(username=username)
    except User.DoesNotExist():
        flag = False
    if flag:
        raise ValidationError(
            '%(value)s is already registered. Double registration is not allowed.',
            params={'value': username}
        )
    try:
        data = get_account(username, type='2')
    except RuntimeError as err:
        raise ValidationError('{}'.format(err))
    try:
        value = data['accounts'][0]['label']
    except (KeyError, IndexError):
        raise ValidationError('%(value)s is not a valid FSEconomy account', params={'value': username})
    if value != username:
        raise ValidationError('%(value)s is not a valid FSEconomy account', params={'value': username})
Beispiel #20
0
    def update_from_data(pool_id, pool_member_data):
        """
    Adds a new member whose username is in `pool_data`.

    Args:
      pool_id: The pool id of an existing pool
      pool_data: Expected to be in the format:
        {"username": <username of new member>}

    Raises:
      User.DoesNotExist: If the user within `pool_data` doesn't exist.
      Pool.DoesNotExist: If the pool doesn't exist.
      TooManyMembersException: If we attempt to add more users than the pool
        can handle.
    """
        # 0. Validate the `pool_data` and `pool_id`.
        assert pool_id.isdigit()
        assert "username" in pool_member_data
        member_username = pool_member_data["username"]
        pool_id = long(pool_id)

        # 1. Validate that a user exists with `member_username`
        user = User.objects.get(username=member_username)
        if not user:
            raise User.DoesNotExist()

        # 2. Attempt to fetch the Pool.
        pool = Pool.objects.get(id=pool_id)
        if not pool:
            raise Pool.DoesNotExist()

        logger.info('pool: %s' % pool)
        # 3. Add the new member to the pool.
        pool.add_member(user)

        logger.info('pool after adding member: %s' % pool.members.all())

        return pool.members.all()
Beispiel #21
0
def get_user(email, **kwargs):
    try:
        name = hash_email(email)
    except UnicodeEncodeError:
        raise User.DoesNotExist()
    return User.objects.get(username=name, **kwargs)
Beispiel #22
0
 def validate_username(self, value):
     if not User.objects.filter(username=value).exists():
         raise User.DoesNotExist("Cannot find username matching '{}'".format(value))
     return value
Beispiel #23
0
 def get_user(self,user_id):
     try:
         return User.objects.get(pk=user_id)
     except User.DoesNotExist():
         return None
Beispiel #24
0
def view_user_doesnotexist(request):  # pylint: disable=W0613
    "A dummy view that raises a User.DoesNotExist exception"
    raise User.DoesNotExist()
Beispiel #25
0
 def user_does_not_exist_side_effect(username="******"):
     raise User.DoesNotExist()