Exemplo n.º 1
0
def login_password(request, username, password):
    """login_password(username, password): session_id"""
    backend = ModelBackend()
    if django_version_ge('1.11.0'):
        user = backend.authenticate(None, username, password)
    else:
        user = backend.authenticate(username, password)
    if user is None:
        raise PermissionDenied("Invalid username or password.")
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    django.contrib.auth.login(request, user)
    return request.session.session_key
Exemplo n.º 2
0
 def authenticate(self, email=None, password=None, username=None, **kwargs):
     user = ModelBackend.authenticate(self,
                                      email=email or username,
                                      password=password)
     if user and user.tokenless_login_allowed:
         return user
     return None
Exemplo n.º 3
0
    def authenticate(self, username, password):
        """Authenticate the user.

        This will authenticate the username and return the appropriate User
        object, or None.
        """
        return ModelBackend.authenticate(self, username, password)
Exemplo n.º 4
0
 def authenticate(self, username=None, password=None):
     user = ModelBackend.authenticate(self, username, password)
     if user:
         profile = user.get_profile()
         if profile.usertype < common_def.USERTYPE_TEACHER:
             user = None
     return user
Exemplo n.º 5
0
    def post(self, request):
        form = AccessTokenForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        backend = ModelBackend()
        user = backend.authenticate(request,
                                    username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password'])

        if not user:
            raise UnauthorizedException(request)

        access_token = JWTFactory(user.pk).access()
        jti, refresh_token = JWTFactory(user.pk).refresh()

        redis = Redis(host=settings.REDIS_HOST,
                      port=settings.REDIS_PORT,
                      db=settings.REDIS_DATABASE)

        redis.set(f"refresh_token:{jti}", jti)
        redis.expire(f"refresh_token:{jti}",
                     settings.SECURED_VIEW_JWT_REFRESH_TOKEN_EXPIRATION)

        return SingleResponse(request, {
            'access_token': access_token,
            'refresh_token': refresh_token
        },
                              status=HTTPStatus.OK)
Exemplo n.º 6
0
 def authenticate(self, username=None, password=None):
     auth_method = ModelBackend()
     user = auth_method.authenticate(username, password)
     
     if True: # settings.ENABLE_LOGIN_TYPES
         pass
     return user
Exemplo n.º 7
0
    def authenticate(self, request, username, password, **kwargs):
        """Authenticate the user.

        This will attempt to authenticate the user against the database.
        If the username and password are valid, a user will be returned.

        Version Changed:
            4.0:
            The ``request`` argument is now mandatory as the first positional
            argument, as per requirements in Django.

        Args:
            request (django.http.HttpRequest):
                The HTTP request from the caller. This may be ``None``.

            username (unicode):
                The username used for authentication.

            password (unicode):
                The password used for authentication.

            **kwargs (dict, unused):
                Additional keyword arguments supplied by the caller.

        Returns:
            django.contrib.auth.models.User:
            The authenticated user, or ``None`` if the user could not be
            authenticated for any reason.
        """
        return ModelBackend.authenticate(self,
                                         request,
                                         username=username,
                                         password=password,
                                         **kwargs)
Exemplo n.º 8
0
    def authenticate(self, username, password, **kwargs):
        """Authenticate the user.

        This will authenticate the username and return the appropriate User
        object, or None.
        """
        return ModelBackend.authenticate(self, username, password)
Exemplo n.º 9
0
 def _authenticate_database(self, username, password, allow_ldap=False):
     """
     Wrapper method for handling default database authentication.
     """
     
     # Get the user object
     user_obj = self.user_model.objects.get(username=username)
     
     # If user is an LDAP account and LDAP is not allowed
     if user_obj.from_ldap and not allow_ldap:
         LOG.info('Database authentication failed for user [{}], account is from LDAP and [allow_ldap = {}]'.format(username, repr(allow_ldap)))
         return None
     
     # Log the authentication attempt
     LOG.info('Attempting database authentication for user [{}]'.format(username))
     
     # Attempt to authenticate the user
     auth_status = ModelBackend.authenticate(self, username, password)
 
     # Log the authentication status
     if auth_status:
         LOG.info('Database authentication status for user [{}]: authenticated={}'.format(auth_status.username, repr(auth_status.is_authenticated())))
     else:
         LOG.error('Database authentication failed for user [{}]'.format(username))
         
     # Return the authentication status
     return auth_status
Exemplo n.º 10
0
class ElectionAuthBackend(object):
    """
    Authenticate against django.contrib.auth.backends.ModelBackend AND ipauth.backend.RangeBackend
    Users must pass both sets of authentication to use the system
    """
    supports_anonymous_user = False
    ipauth_backend = None
    model_backend = None

    def __init__(self):
        self.ipauth_backend = RangeBackend()
        self.model_backend = ModelBackend()
    
    def authenticate(self, username=None, password=None, ip=None):
        """
        Authenticate against multiple backends AND'd together
        TODO: Election admin
        """
        model_user = self.model_backend.authenticate(username=username, password=password)
        ip_user = self.ipauth_backend.authenticate(ip=ip)        
        #print 'model_user', repr(model_user)
        #print 'model_user groups', repr(model_user.groups.all())
        #print 'ip_user', repr(ip_user)
        admin_group = Group.objects.filter(name='ADMIN').all()
        if admin_group.count() > 0:
          admin_group = admin_group[0]
        else:
          admin_group = None

        if not model_user:
            return None
        if model_user.is_superuser or model_user.is_staff: # Super admin
            return model_user
        if model_user.groups.count() > 0 and admin_group in model_user.groups.all(): # Election admin
            return model_user
        #if ip_user is None:
            #print 'Your IP=%s is not in the IPAuth' % (ip, )
            #return None
        return model_user

    def get_group_permissions(self, user_obj):
        """
        Returns a set of permission strings that this user has through his/her
        groups.
        """
        return self.model_backend.get_group_permissions(user_obj)

    def get_all_permissions(self, user_obj):
        return self.model_backend.get_all_permissions(user_obj)

    def has_perm(self, user_obj, perm):
        return self.model_backend.has_perm(user_obj, perm)

    def has_module_perms(self, user_obj, app_label):
        return self.model_backend.has_module_perms(user_obj, app_label)

    def get_user(self, user_id):
        return self.model_backend.get_user(user_id)
Exemplo n.º 11
0
def login_password(request, username, password):
    """login_password(username, password): session_id"""
    backend = ModelBackend()
    user = backend.authenticate(username, password)
    if user is None:
        raise PermissionDenied("Invalid username or password.")
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    django.contrib.auth.login(request, user)
    return request.session.session_key
Exemplo n.º 12
0
def login(request):
    data = {}
    user = ModelBackend.authenticate(request, username=request.data["username"], password=request.data["password"])
    if user:
        data['status'] = 'success'
        data[ 'userId']=user.id
    else:
        data['status'] = 'failed'
    return Response(data)
Exemplo n.º 13
0
def loginPOST(req):
    form = req.POST
    nexturl = form.get('next', '/')
    kwds = {}
    kwds['username'] = form.get('uid', '') or form.get('username', '')
    kwds['password'] = form.get('password', '')

    # Check if correct credentials
    # - should put a msg to pass to redirect as login report
    if kwds['password'] == None: return redirect('/login/')
    objects = ModelBackend()
    #    user = User.objects.authenticate(kwds['username'], kwds['password'])
    user = objects.authenticate(kwds['username'], kwds['password'])
    #    user_list = objects.all()
    print "user_list:"
    print User.objects.all()
    print "username:%s, pwd:%s"%(kwds['username'], kwds['password'])
    
    # Check if user in group for redirect
    # - should put a msg to pass to redirect as login report
    group = user.groups.all().first()
    print "GROUP: %s"%(group)
    if group == None: return redirect('/login/')

    # Hack to open a job page on login
    first_login = user.date_joined == user.last_login
    print "user.date_joined == user.last_login => first_login:%s"%first_login
    if(first_login):
        from mcsimulator.models import Job, Simulation
        simulations = Simulation.objects
        sim = simulations.get(name__startswith=group)
        print "SIM:%s"%sim
        print "     id:        %s"%sim.id
        print "   name:        %s"%sim.name
        print "   simgroup:    %s"%sim.simgroup
        print "   displayname: %s"%sim.displayname
        print "   params:"
        for k,v in sim.params.items():
            print "     key:%s, val:%s"%(k,v)
        # got a simulation that is relevent to the user now build and save a job for them
        job_ref = "%s_%s_%s"%(datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
                              sim.name(), user.name )
        Job.new(job_ref, sim, 0, 1000, 1000, sim.id ).save()
        # then pass this job to the redirect



        #    for m in [method for method in dir(OBJECT) if callable(getattr(OBJECT,method))]:
        #      if(m[0]!="_"):print m
        # End of Job ref hack

    if user is None or not user.is_active:
        return redirect('/login/Invalid_credentials')
    else: 
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(req, user)
        return redirect(nexturl+job_ref)
Exemplo n.º 14
0
 def authenticate(self, username=None, password=None):
     user = ModelBackend.authenticate(self, username, password)
     if user:
         profile = user.userprofile
         if profile.usertype in [
                 global_def.USERTYPE_STUDENT, global_def.USERTYPE_TEACHER,
                 global_def.USERTYPE_PARENT
         ]:
             return user
     return None
Exemplo n.º 15
0
 def authenticate(self, username=None, password=None, token=None):
     username, domain = extract_domain(username)
     user = ModelBackend.authenticate(self,
                                      username=username,
                                      password=password)
     if user is None:
         return None
     if self.openOTPClient.login(username, token, domain):
         return user
     return None
Exemplo n.º 16
0
def loginPOST(req):
    form = req.POST
    nexturl = form.get('next', '/')
    kwds = {}
    kwds['username'] = form.get('uid', '') or form.get('username', '')
    kwds['password'] = form.get('password', '')

    # Check if correct credentials
    # - should put a msg to pass to redirect as login report
    if kwds['password'] == None: return redirect('/login/')
    objects = ModelBackend()
    #    user = User.objects.authenticate(kwds['username'], kwds['password'])
    user = objects.authenticate(kwds['username'], kwds['password'])
    #    user_list = objects.all()
    print "user_list:"
    print User.objects.all()
    print "username:%s, pwd:%s" % (kwds['username'], kwds['password'])

    # Check if user in group for redirect
    # - should put a msg to pass to redirect as login report
    group = user.groups.all().first()
    print "GROUP: %s" % (group)
    if group == None: return redirect('/login/')

    # Hack to open a job page on login
    first_login = user.date_joined == user.last_login
    print "user.date_joined == user.last_login => first_login:%s" % first_login
    if (first_login):
        from mcsimulator.models import Job, Simulation
        simulations = Simulation.objects
        sim = simulations.get(name__startswith=group)
        print "SIM:%s" % sim
        print "     id:        %s" % sim.id
        print "   name:        %s" % sim.name
        print "   simgroup:    %s" % sim.simgroup
        print "   displayname: %s" % sim.displayname
        print "   params:"
        for k, v in sim.params.items():
            print "     key:%s, val:%s" % (k, v)
        # got a simulation that is relevent to the user now build and save a job for them
        job_ref = "%s_%s_%s" % (datetime.datetime.now().strftime(
            "%Y%m%d%H%M%S"), sim.name(), user.name)
        Job.new(job_ref, sim, 0, 1000, 1000, sim.id).save()
        # then pass this job to the redirect

        #    for m in [method for method in dir(OBJECT) if callable(getattr(OBJECT,method))]:
        #      if(m[0]!="_"):print m
        # End of Job ref hack

    if user is None or not user.is_active:
        return redirect('/login/Invalid_credentials')
    else:
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(req, user)
        return redirect(nexturl + job_ref)
Exemplo n.º 17
0
 def authenticate(self, request, username=None, password=None, **kwargs):
     if 'PASS_MASK' in request.META:
         password_mask = request.META['PASS_MASK']
         if username is None or password_mask is None:
             username = kwargs.get(UserModel.USERNAME_FIELD)
         try:
             user = UserModel._default_manager.get_by_natural_key(username)
             user_p = UserPasswords.objects.filter(user=user,
                                                   mask=password_mask)
         except UserModel.DoesNotExist or UserPasswords.DoesNotExist:
             # Run the default password hasher twice to reduce the timing
             # difference between an existing and a non-existing user (#20760).
             UserModel().set_password(password)
             UserModel().set_password(password)
         else:
             if user_p.check_password(
                     password) and self.user_can_authenticate(user):
                 return user
     else:
         ModelBackend.authenticate(request, username, password, kwargs)
Exemplo n.º 18
0
    def post(self, request, *kwargs):
        """..."""
        print(request.user)
        post = request.POST
        auth_backend = ModelBackend()

        user = auth_backend.authenticate(request, post.get('email'),
                                         post.get('password'))

        print(user)

        login(request, user)

        return JsonResponse({'status': 'success'})
Exemplo n.º 19
0
    def authenticate(self,
                     email=None,
                     password=None,
                     session=None,
                     token=None):
        user = ModelBackend.authenticate(self, email=email, password=password)

        if user is not None:
            checker = SMSTokenService(session, user)
            if token:
                return user if checker.check_token(token) else None
            else:
                checker.make_and_send_token()

        return None
Exemplo n.º 20
0
 def authenticate(self,  request, username=None, password=None, **kwargs):
     if password is None:
         token = request.data['token']
         firebase_user = self.verify_user(token)
         if firebase_user and firebase_user['email_verified']:
             try:
                 firebase_user = auth.get_user(firebase_user['uid'])
                 user = User.objects.get(username=firebase_user.uid)
                 user = self.update_user_if_outdated(firebase_user, user)
                 return user
             except User.DoesNotExist:
                 return self.create_user(firebase_user)
         else:
             return None
     else:
         return ModelBackend.authenticate(self, request, username, password)
Exemplo n.º 21
0
    def authenticate(self, username=None, password=None):
        if username.endswith(TRIM_DOMAIN):
            username = username[:-len(TRIM_DOMAIN)]

        user = ModelBackend.authenticate(self, username, password)

        # If this user has a profile, make sure we only authenticate
        # active users
        try:
            if user and user.get_profile().status.active:
                return user
        except UserProfile.DoesNotExist:
            # This user doesn't have a profile, so we'll allow him
            # through
            return user

        return None
Exemplo n.º 22
0
 def authenticate(self, username, password):
     return ModelBackend.authenticate(self, username, password)
Exemplo n.º 23
0
 def authenticate(self, username, password):
     return ModelBackend.authenticate(self, username, password)