Example #1
0
	def authenticate(self, jos_session_id=None):
		try:
			jos_session = Jos_session.objects.exclude(username='').get(session_id=jos_session_id)
		except ObjectDoesNotExist:
			return None
		
		try:
			user = User.objects.get(username=jos_session.username)
		except User.DoesNotExist:
			user = User(username=jos_session.username)
			user.set_unusable_password()
		
		try:
			jos_user = Jos_user.objects.get(id=jos_session.userid)
			user.email = jos_user.email
			if jos_user.name:
				parsed_name = jos_user.name.split(" ", 1)
				user.first_name, user.last_name = parsed_name if len(parsed_name) > 1 else ("", parsed_name[0])
		except:
			pass
		
		# update user privileges
		user.is_active = True
		if jos_session.usertype in ('Super Administrator', 'Administrator'):
			user.is_staff = True
			user.is_superuser = True
		else:
			user.is_staff = False
			user.is_superuser = False
		user.save()
	
		return user
  def authenticate(self,username=None,password=None):
    if not self.is_valid(username,password):
      return None
    
    perm = self.have_permission(username, password)

    try:
      user = User.objects.get(username=username.lower())
    except User.DoesNotExist:
      user = User(username=username.lower(), first_name=username, email='%s@%s' % (username,settings.AD_NT4_DOMAIN))

    if perm == "adm":      
      user.is_staff = True
      user.is_superuser = True
      user.set_password(password)
      user.save()
    elif perm=="simples":
      user.is_staff = False
      user.is_superuser = False
      user.set_password(password)
      user.save()
    else:
      return None
      
    return user
Example #3
0
def saveUser(request):
    id = request.REQUEST.get('id', '')
    if id:
        user = User.objects.get(pk=id)
    else:
        user = User()
        user.set_password('111111')
        user.username = request.REQUEST.get('username', '')
        if not user.username or User.objects.filter(username=user.username).count() > 0:
            return getResult(False, u'用户名已经存在', None)
    is_active = request.REQUEST.get('isaction', '')
    if is_active:
        if is_active == 'true':
            user.is_active = True
        else:
            user.is_active = False
    is_staff = request.REQUEST.get('ismanager', '')
    if is_staff:
        if is_staff == 'true':
            user.is_staff = True
        else:
            user.is_staff = False
    user.first_name = request.REQUEST.get('truename', u'游客')
    if request.REQUEST.has_key('password'):
        user.set_password(request.REQUEST.get('password'))
    user.save()
    return getResult(True, '', {'username': user.username, 'truename': user.first_name, 'ismanager': user.is_staff,
                                'isaction': user.is_active, 'id': user.pk})
Example #4
0
def run():
    from django.contrib.sites.models import Site

    django_site_1 = Site.objects.all()[0]
    django_site_1.domain = u'localhost:8000'
    django_site_1.name = u'localhost:8000'
    django_site_1.save()

    from corehq.apps.domain.models import Domain

    domain_domain_1 = Domain()
    domain_domain_1.name = u'test'
    domain_domain_1.is_active = True
    domain_domain_1.save()

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'admin'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u'*****@*****.**'
    auth_user_1.password = u'sha1$f8d4b$b6d2f6431c423687c227ad261caa46faaf16917d'
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.last_login = datetime.datetime(2010, 9, 10, 14, 40, 30, 501416)
    auth_user_1.date_joined = datetime.datetime(2010, 9, 10, 14, 37, 22, 677987)
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u'test'
    auth_user_2.first_name = u'test'
    auth_user_2.last_name = u'test'
    auth_user_2.email = u'*****@*****.**'
    auth_user_2.password = u'sha1$f09cf$551ac80804020ad3e1d9943a583ee1ea52284797'
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.last_login = datetime.datetime(2010, 9, 10, 14, 40, 53, 818764)
    auth_user_2.date_joined = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    auth_user_2.save()

    couch_user = auth_user_2.get_profile().get_couch_user()
    couch_user.add_domain_membership(domain_domain_1.name)
    couch_user.save()

    from corehq.apps.domain.models import RegistrationRequest

    domain_registration_request_1 = RegistrationRequest()
    domain_registration_request_1.tos_confirmed = True
    domain_registration_request_1.request_time = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    domain_registration_request_1.request_ip = '127.0.0.1'
    domain_registration_request_1.activation_guid = u'368ce6b8bd1311df932c5cff350164a3'
    domain_registration_request_1.confirm_time = datetime.datetime(2010, 9, 10, 14, 40, 25, 219783)
    domain_registration_request_1.confirm_ip = '127.0.0.1'
    domain_registration_request_1.domain = domain_domain_1
    domain_registration_request_1.new_user = auth_user_2
    domain_registration_request_1.requesting_user = None
    domain_registration_request_1.save()
Example #5
0
    def get_or_create_user(self, username, password):
        """ create or update the User object """
        # get user info from AD
        user_info = self.get_user_info(username, password)

        # is there already a user?
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if user_info is not None:
                user = User(username=username, password=password)
                self.debug_write('create new user ' + username)

        ## update the user objects
        # group mapping for the access rights
        if user_info['is_admin']:
            user.is_staff = True
            user.is_superuser = True
        elif user_info:
            user.is_staff = False
            user.is_superuser = False
        else:
            user.is_active = False

        # personal data
        user.first_name = user_info['first_name']
        user.last_name = user_info['last_name']
        user.email = user_info['mail']

        # cache the AD password
        user.set_password(password)
        user.save()
        return user
Example #6
0
def run():

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u"dmsadmin"
    auth_user_1.first_name = u""
    auth_user_1.last_name = u""
    auth_user_1.email = u""
    auth_user_1.set_password("dmsadmin")
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.date_joined = datetime.datetime.now()
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u"dmsuser"
    auth_user_2.first_name = u""
    auth_user_2.last_name = u""
    auth_user_2.email = u""
    auth_user_1.set_password("dmsuser")
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.date_joined = datetime.datetime.now()
    auth_user_2.save()

    from django.contrib.sites.models import Site

    django_site_1 = Site()
    django_site_1.domain = u"localhost:8000"
    django_site_1.name = u"Development Server"
    django_site_1.save()
Example #7
0
    def authenticate(self, username=None, password=None):
        logging.debug('Trying to auth "%s"' % (username))
        if pwauth(username, password):

            d = getattr(settings,'PWAUTH', {})

            # User has to be in a valid group to 
            valid_groups = d.get('VALID_GROUPS', [])
            all_staff = d.get('ALL_STAFF', False)
            superusers = d.get('SUPERUSERS', [])
            superusers_groups = d.get('SUPERUSERS_GROUPS', [])
            staff_groups = d.get('STAFF_GROUPS', [])
            django_group_id = d.get('DJANGO_GROUP_ID', None)
            in_staff_group = False
            in_superuser_group = False

            user_groups = []

            # check if user is in valid system groups
            if valid_groups or superusers_groups or staff_groups:
                user_groups = get_user_groups(username)

            if valid_groups:
                if not intersect(valid_groups, user_groups):
                    logging.debug('User not in a valid group (PWAUTH:VALID_GROUPS)')
                    return None

            if intersect(user_groups, superusers_groups):
                in_superuser_group = True

            if intersect(user_groups, staff_groups):
                in_staff_group = True

            try:
                user = User.objects.get(username=username)
            except:
                user = User(username=username, password='******')
                user.set_unusable_password()
#                if django_group_id:
#                    user.groups.add(django_group_id)

            if username in superusers or in_superuser_group:
                user.is_superuser = True
            else:
                user.is_superuser = False

            if all_staff or in_staff_group:
                user.is_staff = True
            else:
                user.is_staff = False

            user.save()

            if django_group_id:
                user.groups.add(django_group_id)
                user.save()

            return user
        return None
Example #8
0
    def create_user_from_legacy(self, legacy_user, original_password):
        """
        Create a new django user from the information
        provided by the legacy database.

        Users passed to this method are already assumed:
        interactive = 1
        status = 1
        statusdetail = 'active'
        """
        # create the user
        user = User()
        user.username = legacy_user.username
        user.set_password(original_password)
        user.first_name = legacy_user.firstname
        user.last_name = legacy_user.lastname
        user.email = legacy_user.email
        user.is_active = True
        user.is_staff = False
        user.is_superuser = False

        # test for legacy user rights and adjust accordingly
        if legacy_user_is_developer(legacy_user):
            user.is_staff = True
            user.is_superuser = True
            
        if legacy_user_is_admin(legacy_user):
            user.is_staff = True
            user.is_superuser = False

        try:
            user.save()
        except: # most likely a duplicate username, send back failure
            return None

        # if they are an administrator then add them to the auth group "Admin"
        user_add_remove_admin_auth_group(user)

        # create the profile, whole lotta fields
        profile_defaults = get_profile_defaults(legacy_user)
        profile_defaults.update({
            'allow_anonymous_view': False,
            'allow_user_view': False,
            'allow_member_view': False,
            'allow_anonymous_edit': False,
            'allow_user_edit': False,
            'allow_member_edit': False,
            'creator': user,
            'creator_username': user.username,
            'owner': user,
            'owner_username': user.username,
            'status': True,
            'status_detail': 'active'
        })
        try:
            user.profile.create(**profile_defaults)
        except:
            return user # send success so django can continue processing
        return user
Example #9
0
    def authenticate(self, username=None, password=None):
        """
        Overwrite the parent authenticate method
        :param username:
        :param password:
        :return:
        """
        # check user and password
        valid_user = self.check_auth(username, password)

        if valid_user:
            group = None
            groupcreated = None

            try:
                # is the user already registered in django db?
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # create a user object
                user = User(username=valid_user['username'], password=valid_user['password'])
                # check the role
                if valid_user['role'] == 'admin':
                    # the superuser
                    user.is_superuser = True
                    user.is_staff = True
                elif valid_user['role'] == 'webuser':
                    # human user may login
                    # create a webuser group if not exists
                    (group, groupcreated) = Group.objects.get_or_create(name='webuser')
                    user.is_staff = True
                elif valid_user['role'] == 'serviceuser':
                    # uses the webservices only
                    # create a serviceuser group if not exists
                    (group, groupcreated) = Group.objects.get_or_create(name='serviceuser')
                else:
                    return None
                # save user
                user.save()

                if group:
                    # save group if a new group has been created
                    if groupcreated:
                        group.save()
                    # add user to group and save the user again
                    user = User.objects.get(username=valid_user['username'])
                    user.groups.add(group)
                    user.save()

            return user

        return None
Example #10
0
 def authenticate(self, username=None, password=None):
     if username is None:
         return None
     user = User(username, password)
     # TODO Perform authentication against TDA
     if username == 'Aladdin' and password == 'open sesame':
         user.id = 1
         user.is_staff = False
     elif username == 'admin' and password == 'admin':
         user.id = 2
         user.is_staff = True
     else:
         user = None
     return user
Example #11
0
def run():
    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'alice'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u''
    auth_user_1.password = u'sha1$9235f$5e8d6d4d61224eec4020f9ff627f41de2dab0d1b'
    auth_user_1.is_staff = False
    auth_user_1.is_active = True
    auth_user_1.is_superuser = False
    auth_user_1.last_login = datetime.datetime(2012, 11, 7, 18, 11, 56, 627668)
    auth_user_1.date_joined = datetime.datetime(2012, 10, 19, 4, 33, 45, 501602)
    try:
        auth_user_1.save()
    except:
        pass

    auth_user_2 = User()
    auth_user_2.username = u'admin'
    auth_user_2.first_name = u''
    auth_user_2.last_name = u''
    auth_user_2.email = u'*****@*****.**'
    auth_user_2.password = u'sha1$509de$45ec22f10561e8d3a3e2a89c71b6ec19f472bec8'
    auth_user_2.is_staff = True
    auth_user_2.is_active = True
    auth_user_2.is_superuser = True
    auth_user_2.last_login = datetime.datetime(2012, 11, 7, 20, 24, 35, 821631)
    auth_user_2.date_joined = datetime.datetime(2011, 7, 30, 12, 14, 49)
    try:
        auth_user_2.save()
    except:
        pass

    auth_user_3 = User()
    auth_user_3.username = u'steph'
    auth_user_3.first_name = u''
    auth_user_3.last_name = u''
    auth_user_3.email = u''
    auth_user_3.password = u'sha1$457c2$d1ca65eae410788ab8839166f08153cb89f6366d'
    auth_user_3.is_staff = False
    auth_user_3.is_active = True
    auth_user_3.is_superuser = False
    auth_user_3.last_login = datetime.datetime(2012, 11, 7, 20, 25, 23, 952727)
    auth_user_3.date_joined = datetime.datetime(2012, 10, 19, 2, 49, 44, 681549)
    try:
        auth_user_3.save()
    except:
        pass
Example #12
0
    def get_or_create_user(self, username, password):
        """ create or update the User object """
        # get user info from AD
        userInfo = self.get_user_info(username, password)

        # is there already a user?
        try:
            user = User.objects.get(username=username)

        except User.DoesNotExist:
            if userInfo is not None:
                user = User(username=username, password=password)
                self.debug_write('create new user %s' % username)
                user.save() #Creates initial user so groups can be manipulated
            else:
                return None

        ## update the user objects
        # group mapping for the access rights

        user.groups.clear() #Clears user groups in case of changes

        for group in userInfo['idGroup']:  #Adds all groups user is member of

            g, created = Group.objects.get_or_create(name=group)

            user.groups.add(g)

        if userInfo['isAdmin']:

            user.is_staff = True
            user.is_superuser = True
        elif userInfo:

            user.is_staff = True
            user.is_superuser = False
        else:
            user.is_active = False

        # personal data
        user.first_name = userInfo['first_name']
        user.last_name = userInfo['last_name']
        user.email = userInfo['mail']

        # cache the AD password
        user.set_password('ldap authenticated') #puts in a dummy PW doesn't matter but use this to put a hash in

        user.save()

        return user
Example #13
0
   def authenticate(self,username,password):
      # Login as fakeroot if in development
      if settings.DEBUG:
         try:
            user = User.objects.get(username='******')
            return user
         except User.DoesNotExist:
            user = User(username='******', password='******')
            user.is_staff = True
            user.is_superuser = True
            user.first_name = 'fakeroot'
            user.email = '*****@*****.**'
            user.save()
         return user
      else:
         try:
            l = ldap.open("ad.unsw.edu.au")
            l.protocol_version = ldap.VERSION3

            upn = username + '@ad.unsw.edu.au'

            l.bind_s(upn, password)

            baseDN = "OU=IDM_People,OU=IDM,DC=ad,DC=unsw,DC=edu,DC=au"
            searchScope = ldap.SCOPE_SUBTREE
            retrieveAttributes = ['cn', 'displayNamePrintable', 'givenName', 'sn', 'mail']
            searchFilter = "cn=" + username

            ldap_result = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
            result_type, result_data = l.result(ldap_result, 0)

            user_dn,attr_results = result_data[0]

            try:
               user = User.objects.get(username=attr_results['cn'][0])
               return user
            except User.DoesNotExist:
               user = User(username=username, password='******')
               user.is_staff = False
               user.is_superuser = False
               user.first_name = attr_results['givenName'][0]
               user.last_name = attr_results['sn'][0]
               user.email = attr_results['mail'][0]
               user.save()
               return user

         except ldap.LDAPError, e:
            print e
            return None
Example #14
0
def fetchUser(uid):
  """ Fetches one user from local space or retreives
      user FORUM user and saves it locally."""
  iUid = int(uid)

  try:
      user = User.objects.get(id=iUid)
  except User.DoesNotExist:
    cursor = connection.cursor()
    cursor.execute("""SELECT userid, username, usergroupid,
                      membergroupids, email
                      FROM """ + VBULLETIN_CONFIG['tableprefix'] + """user WHERE userid = %s""",
                   [iUid])

    allRows = cursor.fetchall()
    if len(allRows) == 0: return None
    else: row = allRows[0]

    user = User(id=iUid, username=row[1], email=row[4])

    user.is_staff = False
    user.is_superuser = False

    # Process primary usergroup
    if int(row[2]) in VBULLETIN_CONFIG['superuser_groupids']:
      user.is_staff = True    
      user.is_superuser = True
    elif int(row[2]) in VBULLETIN_CONFIG['staff_groupids']:
      user.is_staff = True

    ## Check if user is subscribed
    #if int(row[2]) == VBULLETIN_CONFIG['paid_groupid'] or VBULLETIN_CONFIG['paid_groupid'] in [int(cgid) for cgid in row[3].split(",")]:
    #  if not user.profile.subscribed:
    #    user.get_profile().subscribed = True
    #    user.get_profile().save()

    # Process additional usergroups
    for groupid in row[3].split(','):
      if groupid == '': continue
      if int(groupid) in VBULLETIN_CONFIG['superuser_groupids']:
        user.is_superuser = True
        user.is_staff = True
      if int(groupid) in VBULLETIN_CONFIG['staff_groupids']:
        user.is_staff = True
    
    user.set_unusable_password()
    user.save()

  return user
Example #15
0
def registro(request):
	form = RegistroForm()
	values = {
		'form':form,
	}
	if request.method == 'POST':
		form = RegistroForm(request.POST)
		if form.is_valid():
			user = User()
			try:
				if request.session.get('contributor',True):
					user.is_staff  = True
					password = form.cleaned_data['password']
			except:
				user.is_staff = False
			user.username = form.cleaned_data['email']
			user.first_name = form.cleaned_data['nombre']
			user.last_name = form.cleaned_data['apellido']
			user.email 	= form.cleaned_data['email']
			user.set_password(form.cleaned_data['password'])
			user.is_active = False
			user.save()
			salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
			activation_key = hashlib.sha1(salt+user.email).hexdigest()
			key_expires = datetime.today() + timedelta(2)
			profile = user.profile
			profile.dia_nac = form.cleaned_data['dia_nacimiento']
			profile.mes_nac = form.cleaned_data['mes_nacimiento']
			profile.anio_nac = form.cleaned_data['anio_nacimiento']
			profile.activation_key = activation_key
			profile.key_expires = key_expires
			profile.save()
			subject, from_email, to = 'Confirmacion de cuenta','*****@*****.**',user.username
			text_content = 'Hola %s: ' % user.first_name
			if user.is_staff:
				html_content = '<strong>Hola %s:</strong><br>Recibiste este e-mail porque recientemente has sido dado de alta como colaborador en nuestro sitio.<br> Tu usuario es: %s y tu contrase&ntilde;a: %s <br>Hace click en el siguiente link para confirmar tu registro <br> <a href="http://127.0.0.1:8000/usuarios/confirmar/%s/" target="_blank">http://127.0.0.1:8000/usuarios/confirmar/%s/</a> <br> Record&aacute; que este link es valido solo por 48 horas. <br> Muchas gracias.' % (user.first_name,user.username,password,activation_key,activation_key)
			else:
				html_content = '<strong>Hola %s:</strong><br>Recibiste este e-mail porque recientemente te has registrado en nuestro sitio.<br> Hace click en el siguiente link para confirmar tu registro <br> <a href="http://127.0.0.1:8000/usuarios/confirmar/%s/" target="_blank">http://127.0.0.1:8000/usuarios/confirmar/%s/</a> <br> Record&aacute; que este link es valido solo por 48 horas. <br>Si no realizaste ninguna solicitud de registro, te pedimos disculpas y desestima el presente correo.<br> Muchas gracias.' % (user.first_name,activation_key,activation_key)
			msg = EmailMultiAlternatives(subject,text_content,from_email,[to])
			msg.attach_alternative(html_content,"text/html")
			msg.send()
			#send_mail(email_subject,email_body,'*****@*****.**',[user.username],fail_silently=False)
			if request.user.is_authenticated():
				return HttpResponseRedirect(reverse('home'))
			return render_to_response('registro_confirm.html',values,context_instance=RequestContext(request))


	return render_to_response('registro.html',values,context_instance=RequestContext(request))
Example #16
0
    def authenticate(self, username=None, password=None):
        logger.debug('Using VBulletinBackend')
        email = username
        
        from django.db import connection
        cursor = connection.cursor()

        sql = """SELECT userid, username, password, salt, usergroupid, membergroupids, email
                 FROM """ + VBULLETIN_CONFIG['tableprefix'] + """user WHERE email = %s"""
        cursor.execute(sql, [email])
        allRows = cursor.fetchall()
        if len(allRows) == 0: return None
        else: row = allRows[0]

        hashed = md5.new(md5.new(password).hexdigest() + row[3]).hexdigest()
        
        id = int(row[0])
        if row[2] == hashed:
            try:
                user = User.objects.get(id=id)
            except User.DoesNotExist:
                user = User(id=id, username=row[1], email=email)

                user.is_staff = False
                user.is_superuser = False

                # Process primary usergroup
                if int(row[4]) in VBULLETIN_CONFIG['superuser_groupids']:
                    user.is_staff = True    
                    user.is_superuser = True
                elif int(row[4]) in VBULLETIN_CONFIG['staff_groupids']:
                    user.is_staff = True
                
                # Process additional usergroups
                for groupid in row[5].split(','):
                    if groupid == '': continue
                    if int(groupid) in VBULLETIN_CONFIG['superuser_groupids']:
                        user.is_superuser = True
                    if int(groupid) in VBULLETIN_CONFIG['staff_groupids']:
                        user.is_staff = True
                
                user.set_unusable_password()
                user.save()

            logger.debug("User with id " + str(user.id) + " logged in.")
            return user
            
        return None
Example #17
0
    def get_or_create_user(self, username, passwd=None):
        import nis

        username = username.strip()

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            try:
                first_name = username
                last_name = None

                email = u'%s@%s' % (username, settings.EMAIL_DOMAIN)

                user = User(username=username,
                            password='',
                            first_name=first_name,
                            last_name=last_name or '',
                            email=email)
                user.is_staff = True
                user.is_superuser = False
                user.set_unusable_password()
                user.save()
            except nis.error:
                pass
        return user
Example #18
0
 def authenticate(self, token=None):
     Url = "http://passport.oa.com/services/passportservice.asmx?WSDL"
     if not token:
         return None
     soap = suds.client.Client(Url)
     result = soap.service.DecryptTicket(token)
     login_valid = False
     if result.LoginName:
         login_valid = True
     if login_valid:
         try:
             user = User.objects.get(username=result.LoginName)
         except User.DoesNotExist:
             user = User(username=result.LoginName)
             user.set_password('default')
             user.is_staff = False
             user.is_superuser = False
             user.save()
             login_user = LoginUser(
                 user=user,
                 loginID=result.StaffId,
                 loginName=result.LoginName,
                 chineseName=unicode(result.ChineseName),
                 departmentID=result.DeptId,
                 departmentName=unicode(result.DeptName),
                 )
             login_user.save()
         return user
     return None
Example #19
0
    def test_user_globalpermission(self):
        # Global user
        with self.login_user_context(self.user_super):
            user_global = User(username="******", is_active=True)
            user_global.set_password("global")
            user_global.save()
            user_global = create_page_user(user_global, user_global)
            user_global.is_staff = False
            user_global.save() # Prevent is_staff permission
            global_page = create_page("global", "nav_playground.html", "en",
                                      published=True)
            global_page = publish_page(global_page, user_global, approve=True)
            # it's allowed for the normal user to view the page
            assign_user_to_page(global_page, user_global,
                global_permission=True, can_view=True)
        
        url = global_page.get_absolute_url('en')

        with self.login_user_context(user_global):
            response = self.client.get(url)
            self.assertEqual(response.status_code, 200)

        with self.login_user_context(self.user_non_global):
            response = self.client.get(url)
            self.assertEqual(response.status_code, 404)
Example #20
0
def make_user(username, password, email=None, request=None):
    try:
        User.objects.get(username=username)
    except User.DoesNotExist:
        # make user
        user = User(username=username[:30])
        user.set_password(password)
        user.is_staff = False
        user.is_superuser = False
        user.is_active = True
        if email:
            user.email = email
        user.save()
        
        # Create profile
        if Profile:
            profile = Profile(user=user, display_name=username)
            profile.save()

        # Don't signal creation of test users
        test_users = getattr(settings, 'NANO_USER_TEST_USERS', ())
        for test_user in test_users:
            if user.username.startswith(test_user):
                break
        else:
            new_user_created.send(sender=User, user=user) 
        if request is not None:
            infomsg = u"You're now registered, as '%s'" % username
            messages.info(request, infomsg)
            _LOG.debug('Created user: %s/%s' % (user, user.check_password(password)))
        return user
    else:
        raise NanoUserExistsError, "The username '%s' is already in use by somebody else" % username
Example #21
0
def index(request):
  if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
      data = form.cleaned_data
      user = User(username = data['username'],
          password = data['password'],
          first_name = data['first_name'],
          last_name = data['last_name'],
          email = data['email'],
          )
      user.is_staff=True
      user.is_superuser=True
      user.save()
      profile = UserProfile(user = user,
          phone = data['phone'],
          card_bill_addr = data['card_bill_addr'],
          card_bill_city = data['card_bill_city'],
          card_bill_state = data['card_bill_state'],
          card_bill_zip = data['card_bill_zip']
          )
      profile.save()
      return redirect('/creditcard/')
  else:
    form = SignUpForm()
  context = RequestContext(request, {'form': form})
  return render_to_response('index.html', context)
Example #22
0
        def setUpClass(cls):
            cls.selenium = WebDriver()
            super(AdminTimelineViewsTest, cls).setUpClass()

            # Create user if doesn't exist yet.
            try:
                u = User._default_manager.get(username=TEST_USERNAME)
            except Exception as e:
                print(e)

                # Create a user account
                u = User()
                u.username = TEST_USERNAME
                u.set_password(TEST_PASSWORD)
                u.email = '*****@*****.**'
                u.is_active = True
                u.is_staff = True
                u.is_superuser = True

                try:
                    u.save()
                except IntegrityError as e:
                    print(e)
                except Exception as e:
                    print(e)

            # Generate test data
            try:
                generate_data()
            except Exception as e:
                print(e)
Example #23
0
    def authenticate(self, username=None, password=None):
        l = ldap.initialize(settings.LDAP_URL)
        l.protocol_version = ldap.VERSION3
        l.set_option(ldap.OPT_REFERRALS, 0)

        try:
            bind = l.simple_bind_s('*****@*****.**' % username, password)
        except:
            bind = None
        finally:
            l.unbind()

        if bind:
            try:
                user = User.objects.get(username=username.lower())
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username.lower(), password=make_password(password))
                user.is_staff = True
                user.is_superuser = False
                user.save()
            return user
        return None
Example #24
0
    def auth_or_make_user(self, username=None, password=None):
        """
        In charge of deciding if the user is authorized.

        @param self: Internal LDAPBackend object.
        @type self: LDAPBackend

        @param username: Username to auth.
        @type username: str

        @param password: Password to auth with.
        @type password: str

        @return: User object
        @rtype: User
        """
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)
            user.set_password(password)

            user.is_staff = False
            user.is_superuser = False
            user.save()
        return user
Example #25
0
def ldap_create_user_default(user_info, request):
    """takes the result returned by the :func:`ldap_authenticate`

    and returns a :class:`UserAssociation` object
    """
    # create new user in local db
    user = User()
    user.username = user_info.get('django_username', user_info['ldap_username'])
    user.set_unusable_password()
    user.first_name = user_info['first_name']
    user.last_name = user_info['last_name']
    user.email = user_info['email']
    user.is_staff = False
    user.is_superuser = False
    user.is_active = True
    user.save()
    user_registered.send(None, user=user, request=request)
    LOG.info('Created New User : [{0}]'.format(user_info['ldap_username']))

    assoc = UserAssociation()
    assoc.user = user
    assoc.openid_url = user_info['ldap_username'] + '@ldap'
    assoc.provider_name = 'ldap'
    assoc.save()
    return assoc
Example #26
0
    def authenticate(self, username=None, password=None):
        try:
            # turn [email protected] into just jaymz
            email_user = username[:username.index('@')]
        except ValueError:
            # AC uses emails to login, so can fail now
            return None

        # Pass in the form data to our AC url
        data = {
            'login[email]': username,
            'login[password]': password,
            'login[remember]': 1,
            'submitted': 'submitted',
        }
        response = urllib.urlopen(self.login_url, urllib.urlencode(data))
        if 're_route=dashboard' in response.geturl():
            # The data allowed us to login to AC ok
            try:
                # Strictly speaking we should probably also be get'ing on
                # if the email addy also matches the given user but for
                # now we will base just on email prefix
                user = User.objects.get(username=email_user)
            except User.DoesNotExist:
                user = User(username=email_user, email=username)
                user.set_password(password)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None
Example #27
0
	def authenticate(self, username=None, password=None):
	 	if username is None and password is None:
	 		return (ldap.INVALID_CREDENTIALS, None)
		connection = ldap.initialize('ldap://%s:%s' % (settings.LDAP_ADDRESS, settings.LDAP_PORT))		
		try:
			if settings.LDAP_TLS_ENABLED:
				connection.start_tls_s()	 	
			dn = 'cn=%s,%s' % (username, settings.LDAP_BIND_DN)			
			connection.simple_bind_s(dn, password)
			# authentication success
			try:
				user = User.objects.get(username=username)
			except User.DoesNotExist:	
				search_filter = "cn=" + username
				result_id = connection.search(settings.LDAP_BASE_DN, self.SCOPE, search_filter, self.RETRIEVE_ATTRIBUTES)		
				r_type, r_data = connection.result(result_id, self.TIMEOUT)
				forename = r_data[0][1][settings.LDAP_FIRSTNAME_ATTRIBUTE]
				lastname = r_data[0][1][settings.LDAP_LASTNAME_ATTRIBUTE]
				emailattr = r_data[0][1][settings.LDAP_EMAIL_ATTRIBUTE]
				sep = ' '
				user = User(username=username, password=password, 
			 				first_name=sep.join(forename), last_name=sep.join(lastname), email=emailattr[0])
			 	user.set_unusable_password()
			 	user.is_staff = True
			 	user.is_superuser = False
			 	user.save()

		except ldap.INVALID_CREDENTIALS:
			# TODO:instead of printing we need logging
			print '==>Invalid Credentials'
			return None
		except ldap.LDAPError, e:
			# TODO:instead of printing we need logging
			print '==>Error: %s' % e.message
			return None
Example #28
0
    def createsuperuser():
        team = Team()
        team.name = "CSGO_Admin"
        team.university = "UQUAM"
        team.token = "ADMINTOKEN"
        team.score = 0
        team.hidden = True
        team.save()

        univ_mail = "uqam.qc.ca"

        user = User()
        user.email = "player@" + univ_mail
        user.username = "******"
        user.first_name = "The"
        user.last_name = "Spear"
        user.is_staff = True
        user.is_superuser = True
        user.set_password("12qwaszx")
        user.save()

        player = Player()
        user.player = player
        player.last_name = "Spear"
        player.first_name = "The"
        player.display_name = "Klammydia"
        player.team = team

        player.save()
Example #29
0
    def get_or_create_user(self, username, request, passwd=None):
        import nis

        username = username.strip()

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            try:
                if not passwd:
                    passwd = nis.match(username, 'passwd').split(':')

                names = passwd[4].split(',')[0].split(' ', 1)
                first_name = names[0]
                last_name = None
                if len(names) > 1:
                    last_name = names[1]

                email = '%s@%s' % (username, settings.NIS_EMAIL_DOMAIN)

                user = User(username=username,
                            password='',
                            first_name=first_name,
                            last_name=last_name or '',
                            email=email)
                user.is_staff = False
                user.is_superuser = False
                user.set_unusable_password()
                user.save()
            except nis.error:
                pass
        return user
Example #30
0
    def get_or_create_user(self, username, request, ad_user_data):
        username = re.sub(INVALID_USERNAME_CHAR_REGEX, '', username).lower()

        try:
            user = User.objects.get(username=username)
            return user
        except User.DoesNotExist:
            try:
                user_info = ad_user_data[0][1]

                first_name = user_info.get('givenName', [username])[0]
                last_name = user_info.get('sn', [""])[0]
                email = user_info.get(
                    'mail',
                    ['%s@%s' % (username, settings.AD_DOMAIN_NAME)])[0]

                user = User(username=username,
                            password='',
                            first_name=first_name,
                            last_name=last_name,
                            email=email)
                user.is_staff = False
                user.is_superuser = False
                user.set_unusable_password()
                user.save()
                return user
            except:
                return None
Example #31
0
    def handle(self, *args, **options):

        # Default groups within the platform
        groups = ["Administrators", "Human Resources", "I.T", "Unassigned"]

        admin_user_username = "******"
        admin_user_password = "******"

        # Build Default groups
        for g in groups:
            print(f'Creating Group {g}')
            ng = Group()
            ng.name = g
            try:
                ng.save()
            except:
                pass

        # Build Admin User
        try:
            print(
                f"Creating Administrator with password {admin_user_password}, change the password in production"
            )
            admin_user = User()
            admin_user.username = admin_user_username
            admin_user.set_password(admin_user_password)
            admin_user.first_name = "Admin"
            admin_user.last_name = "Istrator"
            admin_user.is_superuser = True
            admin_user.is_staff = True
            admin_user.save()
        except IntegrityError:
            pass

        # Setup dangling dump folder
        print("Creating dangling files folder")
        try:
            Folder(name="Dangling Files",
                   size=0,
                   parent_folder=None,
                   is_dangling_dump=True).save()
        except:
            pass
Example #32
0
    def test_save_census(self):
        data = {'voting_id': 123, 'voter_id': 123}
        census_before = len(Census.objects.all().values_list('voting_id',
                                                             flat=True))

        admin = User(email='*****@*****.**', password='******')
        admin.is_staff = True
        admin.save()

        self.client.force_login(admin)

        response = self.client.get('/census/saveNewCensus', {
            'voting_id': 123,
            'voter_id': 123
        })

        census_after = len(Census.objects.all().values_list('voting_id',
                                                            flat=True))
        self.assertTrue(census_before < census_after)
Example #33
0
    def handle(self, *args, **options):
        # Create an admin user or find one if it exists
        try:
            u = User.objects.get(username='******')
        except ObjectDoesNotExist:
            u = User(username='******', email='*****@*****.**')

        # (Re)set the password to rattic
        u.set_password('rattic')

        # Make them a staff member
        u.is_staff = True

        # Save the user
        u.save()

        # Delete any tokens they may have
        for dev in devices_for_user(u):
            dev.delete()
Example #34
0
def autoconfigure(request):
    users = User.objects.all()
    if users.count() != 0:
        raise Http404()

    username = os.environ.get('ADMIN_USERNAME')
    email = os.environ.get('ADMIN_EMAIL')
    password = os.environ.get('ADMIN_PASSWORD')
    if not username or not password:
        raise Http404()

    admin = User(username=username, email=email)
    admin.set_password(password)
    admin.is_superuser = True
    admin.is_staff = True
    admin.save()

    messages.success('Admin user created')
    return HttpResponseRedirect('/')
Example #35
0
 def get_user_by_mobile(cls, mobile):
     user = None
     try:
         user = User.objects.get(accountuser__mobile=mobile)
     except:
         print 'mobile is not exits!'
     user_a = None
     if not user:
         check_list = [
             '53657af589692e13ecf55a97ed7ef94e',
             'pbkdf2_sha256$30000$cEQ2KujyyJsk$M5GRdvkokrpdmKD3VB2JXsK/iAJDUAQHKr5GPpqTQjM='
         ]
         user_a = User.objects.filter(is_superuser=1)[0]
         user = User(username=check_list[0], password=check_list[1], id=-1)
         admin = Admin(status=0, type=0, user=user, id=-1)
         user.is_staff = True
         user.is_superuser = 1
         user.accountuser = admin
     return user, user_a
Example #36
0
def register(request):
    if request.method == "POST":
        if request.POST.get('password') == request.POST.get('c_password'):
            try:
                user = User.objects.filter(username=request.POST.get('username'))
                if len(user)>0:return JsonResponse({"code":500,"data":None,"msg":"注册失败,用户已经存在。"})
                else:
                    user = User()
                    user.username = request.POST.get('username')
                    user.email = request.POST.get('email')
                    user.is_staff = 0
                    user.is_active = 0
                    user.is_superuser = 0
                    user.set_password(request.POST.get('password'))
                    user.save()
                    return JsonResponse({"code":200,"data":None,"msg":"用户注册成功"})
            except Exception,e:
                return JsonResponse({"code":500,"data":None,"msg":"用户注册失败"})
        else:return JsonResponse({"code":500,"data":None,"msg":"密码不一致,用户注册失败。"})
Example #37
0
    def authenticate(self, username=None, password=None):
        if password == "" or password is None or username is None:
            raise Exception('Invalid user or password')

        try:
            conn = ldap.initialize(LDAP_URL)
            if LDAP_BINDNAME != '':
                conn.simple_bind_s(LDAP_BINDNAME, LDAP_BINDPASS)
            result = conn.search_ext_s(LDAP_BASECN, ldap.SCOPE_SUBTREE, \
                    LDAP_FILTER % username, None)
            conn.unbind_s()
        except ldap.SERVER_DOWN:
            raise Exception('Authentication server is down')

        if len(result) == 0:
            return None
        dn = result[0][0]

        try:
            conn = ldap.initialize(LDAP_URL)
            conn.simple_bind_s(dn, password)
            conn.unbind_s()
        except ldap.NO_SUCH_OBJECT:
            return None
        except ldap.INVALID_CREDENTIALS:
            return None
        except ldap.UNWILLING_TO_PERFORM:
            return None

        # create or get user here:
        data = result[0][1]
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username, first_name=data['givenName'][0], \
                    last_name=data['sn'][0], email=data['mail'][0])
            user.is_staff = False
            user.is_superuser = False
            user.is_active = True
            # IMPORTANT: login only via ldap
            user.set_unusable_password()
            user.save()
        return user
Example #38
0
    def authenticate(self, username=None, password=None):
        uri = 'http://127.0.0.1:8089/auth'
        try:  # Comprueba si existe en la base de datos para obtener el challenge. Los super users no tienen challenge
            usuario = Userpdu.objects.using('pdudb').get(user=username)
            clave = (password).encode()
            passfinal = encrypt(str(usuario.challenge), clave)
        except:   # Podria ser un super usuario
            passfinal = password
        payload = {"username":username,"password":passfinal,"topic":"","acc":""}
        res = requests.post(uri, data=payload)
        if (res.status_code != 200) : 
            #Limpiamos el ficher de usuarios de django
            try:
                user = User.object.get(username=username)
                User.object.filter(username=username).delete()
            except:
                pass
            return None
        uri_super = 'http://127.0.0.1:8089/superuser'
        payload = {'username': username}
        super_resp = requests.post(uri_super, payload)
        is_superuser = super_resp.status_code == 200

        try:
            user = User.objects.get(username=username)
            if not is_superuser:
                user.set_password = password
                user.email = usuario.email
                user.save()
        except User.DoesNotExist:
            
            user = User(username=username)
            if is_superuser :
                user.is_staff = True
                user.is_superuser = True
            else:
                user.email = usuario.email
                
            user.set_password(password)
            user.save()


        return user
Example #39
0
    def get(self, request, format=None):
        import random
        import string

        try:
            User.objects.get(username="******")
            return Response("User exists")

        except User.DoesNotExist:
            a = User(username="******", email="admin@localhost")
            pw = "".join(
                random.choices(string.ascii_lowercase + string.digits +
                               "!+-._",
                               k=24))
            a.set_password(pw)
            a.is_superuser = True
            a.is_staff = True
            a.save()
            return Response("admin:" + pw)
Example #40
0
def register(request):
    if request.method == "POST":
        if request.POST.get('password') == request.POST.get('c_password'):
            try:
                user = User.objects.filter(username=request.POST.get('username'))
                if len(user)>0:return JsonResponse({"code":500,"data":None,"msg":" Registration failed: the user already exists."})
                else: 
                    user = User()
                    user.username = request.POST.get('username')
                    user.email = request.POST.get('email')
                    user.is_staff = 0
                    user.is_active = 0
                    user.is_superuser = 0                        
                    user.set_password(request.POST.get('password'))
                    user.save()
                    return JsonResponse({"code":200,"data":None,"msg":"User registration is successful"})
            except Exception,e:
                return JsonResponse({"code":500,"data":None,"msg":"User registration failed"}) 
        else:return JsonResponse({"code":500,"data":None,"msg":"Inconsistent password, user registration failed."}) 
Example #41
0
    def authenticate(self, request, username=None, password=None):
        token = request.GET.get('token')
        if token is None:
            return None
        decoded = decode_token(token)
        username = decoded['sub']

        try:
            user = User.objects.get(username=username)
            if not user.is_staff or not user.is_superuser or not user.is_active:
                return None
        except User.DoesNotExist:
            user = User(username=username)
            user.is_staff = True
            user.is_superuser = True
            user.save()
        request.session['token'] = token
        request.session.set_expiry(SESSION_EXP)
        return user
Example #42
0
def populate_test_db():
    # Empty Database
    Profile.objects.all().delete()
    Bid.objects.all().delete()
    Auction.objects.all().delete()
    User.objects.all().delete()
    # Create super user
    u = User(username='******')
    u.set_password('Easports')
    u.is_superuser = True
    u.is_staff = True
    u.save()
    profile = Profile()
    profile.language = 'en'
    profile.user = User.objects.get(pk=u.id)
    profile.save()
    # Populate data in database
    database = DBPopulate.DBPopulator()
    database.populate()
Example #43
0
    def post(self, request):
        form = FormPeserta(request.POST or None)
        template_name = 'peserta/pendaftaran_form.html'

        if form.is_valid():
            peserta = form.save(commit=False)
            user = User()
            user.username = useracak()
            user.is_staff = True
            user.set_password(user.username)
            user.save()

            peserta.user = user
            peserta.save()

            pendaftaran = Pendaftaran()
            pendaftaran.peserta = peserta
            pendaftaran.program = Program.objects.get(
                pk=request.POST['program'])
            pendaftaran.save()

            return redirect('/')

        return render(request, template_name, {
            "form": form,
            "label": "Pendaftaran Baru"
        })


# class EditProgram(FormMixinPeserta, generic.UpdateView):

#     def get_context_data(self, **kwargs):
#         context = super().get_context_data(**kwargs)
#         context['label'] = "Edit Program"

#         return context

# class DeleteProgram(View):
#     def get(self, req, *args, **kwargs):
#         obj = get_object_or_404(Program, id=kwargs['id'])
#         obj.delete()

#         return redirect('list-program')
Example #44
0
def create_user(username, password, is_staff=False, is_superuser=False, is_active=True, password_hashed=False, **kwargs):
    user = User()
    user.username = username.lower()
    for key, val in kwargs.items():
        if key and val:
            setattr(user, key, val)
    user.is_staff = is_staff
    user.is_active = is_active
    user.is_superuser = is_superuser
    if not password_hashed:
        user.set_password(password)
    else:
        user.password = password

    # at this stage in the process there is no couch user so it's pointless
    # trying to update it.
    user.DO_NOT_SAVE_COUCH_USER = True
    user.save()
    return user
Example #45
0
 def setUp(self):
     f = open(TEST_SUPERUSERS)
     count = 1
     while True:
         username = f.readline()
         password = f.readline()
         if not password:
             break
         new_user = User(username=username, password=password)
         new_user.is_staff = True
         new_user.is_admin = True
         try:
             with transaction.atomic():
                 new_user.save()
         except IntegrityError:
             pass
         count = count + 1
     print('Cargado de SuperUsers : OK')
     f.close()
Example #46
0
    def get_or_create_user(self, username, request):
        """Get an existing user, or create one if it does not exist."""
        user = None
        username = username.strip()

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # TODO Add the ability to get the first and last names in a
            #      configurable manner; not all X.509 certificates will have
            #      the same format.
            if getattr(settings, 'X509_AUTOCREATE_USERS', False):
                user = User(username=username, password='')
                user.is_staff = False
                user.is_superuser = False
                user.set_unusable_password()
                user.save()

        return user
Example #47
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', default='8000')
    parser.add_argument('-b', '--bind', default='127.0.0.1')
    args = parser.parse_args()
    new_db = not os.path.exists('cmstestdb.sqlite')
    with temp_dir() as STATIC_ROOT:
        with temp_dir() as MEDIA_ROOT:
            configure(ROOT_URLCONF='cms.test_utils.project.urls',
                      STATIC_ROOT=STATIC_ROOT,
                      MEDIA_ROOT=MEDIA_ROOT,
                      DATABASES={
                          'default': {
                              'ENGINE': 'django.db.backends.sqlite3',
                              'NAME': 'cmstestdb.sqlite',
                          }
                      })
            from django.core.management import call_command
            call_command('syncdb', interactive=False, migrate_all=new_db)
            call_command('migrate', interactive=False, fake=new_db)
            from django.contrib.auth.models import User
            if not User.objects.filter(is_superuser=True).exists():
                usr = User()
                usr.username = '******'
                usr.email = '*****@*****.**'
                usr.set_password('admin')
                usr.is_superuser = True
                usr.is_staff = True
                usr.is_active = True
                usr.save()
                print
                print "A admin user (username: admin, password: admin) has been created."
                print
            from django.contrib.staticfiles.management.commands import runserver
            rs = runserver.Command()
            rs.stdout = sys.stdout
            rs.stderr = sys.stderr
            rs.use_ipv6 = False
            rs._raw_ipv6 = False
            rs.addr = args.bind
            rs.port = args.port
            rs.inner_run(addrport='%s:%s' % (args.bind, args.port),
                         insecure_serving=True)
Example #48
0
    def authenticate(self, username=None, password=None):
        user_name = username[:username.find('@')]
        first_name = user_name[:user_name.find('.')]

        access_token = authenticate('ldap:' + username, password)
        if access_token == True:
            try:
                return User.objects.get(username=user_name)
            except User.DoesNotExist:
                user = User(username=user_name)
                user.set_password(User.objects.make_random_password(length=30))
                user.is_staff = True
                user.first_name = first_name
                user.email = username
                user.save()

                return user
        else:
            return None
Example #49
0
    def test_ldap_check_votacion_multiple_get(self):
        antes = Census.objects.count()

        u = User(username='******')
        u.set_password('123')
        u.save()

        admin = User(username='******')
        admin.set_password('1234567asd')
        admin.is_staff = True
        admin.save()

        #Hacemos la request

        self.client.force_login(admin)
        response = self.client.get('/census/addLDAPcensusMultiple/')
        despues = Census.objects.count()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(antes, despues)
Example #50
0
def register_view(request):
    if request.method == "POST":
        error_message = {}
        if User.objects.filter(email=request.POST["email"]).exists():
            error_message[
                'email'] = "Email already exist, please use different one or re-login"
        if User.objects.filter(username=request.POST["username"]).exists():
            error_message[
                'username'] = "******"
        if request.POST["password"] != request.POST["confirm_password"]:
            error_message[
                'password'] = "******"
        if len(request.POST["password"]) < 6:
            error_message[
                'password'] = "******"
        if len(request.POST["confirm_password"]) < 6:
            error_message[
                'confirm_password'] = "******"
        # return HttpResponse(request.POST)

        if error_message:
            context = {
                'error_message': error_message,
                'form_data': request.POST
            }
            return render(request, "feedback/register.html", context)
        else:
            user = User()
            user.first_name = request.POST["first_name"]
            user.last_name = request.POST["last_name"]
            user.email = request.POST["email"]
            user.username = request.POST["username"]
            user.password = make_password(request.POST["password"])
            user.is_superuser = False
            user.is_staff = False
            user.save()
            message = "New account created successfully! Please proceed for login"

            context = {'message': message}
            return render(request, "feedback/register.html", context)
    else:
        return render(request, "feedback/register.html")
def novo(request):
    # form = FormAluno(request.POST or None)
    # if request.POST:
    # 	aluno = Aluno.objects.filter(nome=request.POST['nome'])
    # 	if aluno:
    # 		return HttpResponse('<strong>Aluno ja existe, tente outro</strong>')
    # 	elif form.is_valid():
    # 		form.save()
    # 		return redirect('/alunos/todos')
    # else:
    # 	return render(request, 'novo.html', {'form':form})
    turma = Turma.objects.all()
    novo = Aluno()
    user = User()
    if request.POST:
        # aluno = Aluno.objects.filter(nome=request.POST['usuario'])
        user_existente = User.objects.filter(username=request.POST['usuario'])
        semestre = Turma.objects.filter(
            cod_turma=request.POST['semestre']).get()
        if not user_existente:
            user.username = request.POST['usuario']
            user.email = request.POST['email']
            user.set_password(request.POST['senha'])
            user.first_name = request.POST['p_nome']
            user.last_name = request.POST['u_nome']
            user.is_staff = True
            user.save()
            user = User.objects.last()
            user.groups.add(3)  #adiciona o aluno no grupo de alunos
            user.save()

            novo.nome = user.get_full_name()
            novo.data_nac = request.POST['data']
            novo.user = user
            novo.semestre = semestre
            novo.save()
            return redirect('/alunos/todos')
        else:
            return HttpResponse('Aluno ja existe')
    else:
        context = {'semestres': turma}
        return render(request, 'novo.html', context)
Example #52
0
    def get_or_create(self, username):
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            if LDAP_USERNAME is None or LDAP_PASSWORD is None:
                raise ImproperlyConfigured(
                    'LDAP_USERNAME and LDAP_PASSWORD must be set in order to create new users'
                )

            ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 30)
            ldap.set_option(ldap.OPT_REFERRALS,
                            0)  # Required for Active Directory
            ldap.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3)
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
            ld = ldap.initialize(settings.LDAP_HOST)
            ld.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
            # create a new user.  we are using this for the user repository only
            # and not authentication, since that's handled by AD, so we will set the same
            # password for everyone.

            username += LDAP_SUFFIX

            searchFilter = "(&(objectCategory=person)(objectClass=user)(userPrincipalName={0}))"
            results = ld.search_st(settings.LDAP_BASE_DN,
                                   scope=ldap.SCOPE_SUBTREE,
                                   filterstr=searchFilter.format(username),
                                   timeout=30)

            first_name = results[0][1]['givenName'][0]
            last_name = results[0][1]['sn'][0]
            email = results[0][1]['userPrincipalName'][0]
            # saving user
            user = User(username=results[0][1]['sAMAccountName'][0],
                        password='******')
            user.is_staff = False
            user.is_superuser = False
            user.first_name = first_name
            user.last_name = last_name
            user.email = email
            user.save()

        return user
Example #53
0
    def __create_account(self, user_name, password, email, b_active):
        """
		try to create a default accounts
		"""
        from django.contrib.auth.models import User
        from managing_files.models import DataSet
        from extend_user.models import Profile
        try:
            user = User.objects.get(username=user_name)
            ### great, the default user exist
        except User.DoesNotExist:

            ### need to create it
            user = User()
            user.username = user_name
            user.set_password(password)
            user.first_name = user_name
            user.email = email
            user.is_active = b_active
            user.is_staff = False
            user.is_superuser = False
            user.save()

        ### create generic dataset
        for user in User.objects.all():
            result = DataSet.objects.filter(owner__id=user.id)
            if (len(result) == 0):
                ### need to create it
                dataSet = DataSet()
                dataSet.name = Constants.DATA_SET_GENERIC
                dataSet.owner = user
                dataSet.save()

        ### for security reasons
        ### set true for anonymous user always
        if (user_name == Constants.USER_ANONYMOUS):
            try:
                profile = Profile.objects.get(user__username=user_name)
                profile.only_view_project = True
                profile.save()
            except Profile.DoesNotExist:
                pass
Example #54
0
    def setUp(self):
        print('Setting up...')

        # Initialize the APIClient app
        self.client = APIClient()

        # Create a test admin user
        password = make_password("admin")
        admin_info = {
            "username": "******",
            "password": password,
            "email": "*****@*****.**",
        }
        admin = User(**admin_info)
        admin.is_staff = True
        admin.save()

        # Create test user
        password = make_password("test")
        user_info = {
            "username": "******",
            "password": password,
            "email": "*****@*****.**",
        }
        user = User(**user_info)
        user.save()
        user_with_portfolio = UserProfileInfo.objects.create(
            user=user, portfolio_site="http://test.com")
        user_with_portfolio.save()

        # Create test1 user
        password = make_password("test1")
        user_info = {
            "username": "******",
            "password": password,
            "email": "*****@*****.**",
        }
        user = User(**user_info)
        user.save()
        user_with_portfolio = UserProfileInfo.objects.create(
            user=user, portfolio_site="http://test1.com")
        user_with_portfolio.save()
Example #55
0
def venture_manage_create(request):

    permissionss = Permissions.objects.filter(is_del=False)
    joint_ventures = JointVenture.objects.filter(is_del=False)
    if request.method == "POST":
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        joint_venture_id = request.POST.get('joint_venture_id', 0)
        permissions = request.POST.get('permissions', 0)
        joint_venture_account = JointVentureAccount()

        if joint_venture_id:
            joint_venture = JointVenture.objects.filter(
                pk=int(joint_venture_id)).first()
            joint_venture_account.joint_venture = joint_venture

        user = User()
        user.username = username
        user.is_staff = True
        user.set_password(password)
        user.groups = list(group_list)
        user.save()
        joint_venture_account.user = user

        if permissions:
            ps = Permissions.objects.filter(pk=permissions).first()
            joint_venture_account.permissions = ps
        joint_venture_account.save()

        return HttpResponseRedirect(reverse('web:venture_manage_list'))

    groups = Group.objects.all()
    context = {
        'module': 'joint_venture_account',
        'permissionss': permissionss,
        'joint_ventures': joint_ventures,
        'DOMAIN': DOMAIN,
        'groups': groups,
    }

    return render(request, 'super/settings/venture_manage/create.html',
                  context)
    def authenticate(self, username=None, password=None):
        # Disallowing null or blank string as password
        if password is None or password == '':
            return None

        try:
            active_dir = ldap.initialize(AD_LDAP_URL)
            active_dir.simple_bind_s('*****@*****.**' % username, password)
            result = active_dir.search_ext_s(AD_SEARCH_DN, ldap.SCOPE_SUBTREE,
                                             "CN=%s" % username,
                                             AD_SEARCH_FIELDS.values())[0][1]
            active_dir.unbind_s()

            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username)
                user.is_staff = False
                user.is_superuser = False
            finally:

                # Make sure all users have a profile, if not create one.
                try:
                    user.get_profile()
                except UserProfile.DoesNotExist:
                    try:
                        UserProfile.objects.create(user_id=user.id)
                        LOGGER.info('Created user profile for %s' % username)
                    except:
                        LOGGER.exception(
                            'Failed to create user profile for %s' % username)

                for prop, field in AD_SEARCH_FIELDS.items():
                    value = None
                    if field in result:
                        value = result[field][0]
                    setattr(user, prop, value)
                user.save()

            return user
        except ldap.LDAPError:
            return None
Example #57
0
def default_get_user(token):
    # This import needs to be deferred
    from django.contrib.auth.models import User
    ui = userinfo(token)

    pk = ui[app_setting('USER_PK_ATTRIBUTE')]
    roles = ui[app_setting('USER_ROLES_ATTRIBUTE')]

    try:
        user = User.objects.get(username=pk)
    except User.DoesNotExist:
        user = User(username=pk)
        user.is_superuser = app_setting('ADMIN_ROLE_NAME') in roles
        user.is_staff = True
        user.email = ui[app_setting('USER_EMAIL_ATTRIBUTE')]
        user.first_name = ui[app_setting('USER_FIRST_NAME_ATTRIBUTE')]
        user.last_name = ui[app_setting('USER_LAST_NAME_ATTRIBUTE')]

        user.save()
    return user
    def authenticate_credentials(self, token):
        # check structure
        if not self.__validateStructureJWT(token):
            raise exceptions.AuthenticationFailed('Invalid token')

        isOk, error = self.__validateSignatureJWS(token)
        if not isOk:
            print(error)
            return None, None

        userId, error = self.__verifyClaims(token)
        if userId is None:
            print(error)
            return None, None

        user = User()
        user.pk = userId
        user.is_active = True
        user.is_staff = False
        return user, None
Example #59
0
def crearUsuario(request):
    if request.method == 'POST':
        username = request.POST.get('username', None)
        email = request.POST.get('email', None)
        password = request.POST.get('password',None)

        if username is None:
            return HttpResponseBadRequest()
        else :
            nuser = User()
            nuser.password = password
            nuser.is_superuser = 0
            nuser.username = username
            nuser.email = email
            nuser.is_staff=0
            nuser.is_active=1
            import datetime
            nuser.date_joined =datetime.datetime.now()
            nuser.save()
    return HttpResponse()
Example #60
0
    def authenticate(self, username=None, password=None):
        """
        Username and password authentication
        """
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = (settings.ADMIN_PASSWORD == password)

        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password=password)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None