Example #1
0
    def authenticate(self, auth_code=None):
        authenticator = get_authenticator()
        authenticator.set_token(auth_code)

        foursquare_user = psq.UserFinder(authenticator).findUser('self')
        username = '******' % foursquare_user.id()

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = User(username=username)
            user.set_unusable_password()

        # Update the user's settings so they stay in sync with Foursquare
        user.email = foursquare_user.email()
        user.first_name = foursquare_user.first_name()
        user.last_name = foursquare_user.last_name()
        user.save()

        # Stash the access token on the user's profile
        profile = user.get_profile()
        profile.access_token = authenticator.access_token
        profile.save()

        # Update the user's list of visited venues
        #TODO This doesn't need to be in the request cycle for returning users
        profile.update_visited_venues()

        return user
def add_user(user_details):
    # Does user already exist?
    try:
        u = User.objects.get(username=user_details['username'])
        log.warn("Username '%s' already exists. Not overwriting." % user_details['username'])
        return False
    except User.DoesNotExist:
        # parameter cleanup
        username=user_details['username'][:30]
        name = user_details.get('name', '')[:70]
        first_name = user_details.get('firstname', '')[:30]
        last_name = user_details.get('lastname', '')[:30]
        email = user_details.get('email','')[:40]
        u = User(username=username, 
                 first_name=first_name,
                 last_name=last_name,
                 email=email )

        u.set_password(user_details.get('password', ''))
        if user_details.get('password', '') == '':
            u.set_unusable_password()
            log.warn("User: '******' hasn't supplied a usable password. Marking as such.'")

        u.save()
        # (Create and) set the name in the profile to the one supplied
        u.profile.name = name
        u.profile.save()
        u.save()
        
    return True
Example #3
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 #4
0
	def authenticate(self, token=None):
		token_valid = self.validateToken(token)
		if token_valid:
			try:
				userJson = self.getUserInformation(token)
				roles = []
				#for item in userJson["roles"]:
				#   roles.append(item["name"])

				user = User.objects.get(username= userJson['id'])
				user.email = userJson["email"]
				org_list = userJson["organizations"]
				user.organizations = []
				for org in org_list:
					if org['roles']:
						user.organizations.append(org)
				user.roles = []
				for role in userJson["roles"]:
					user.roles.append(role["name"])
			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= userJson['id'])
				user.set_unusable_password()
				user.is_staff = False

				user.is_superuser = False
				user.save()
			return user
		return None
Example #5
0
def user_signup(request):
	if request.user.is_authenticated():
		return redirect('joust-selfserve-tournament')
	#process form
	if request.POST:
		signupform = forms.UserSignupForm(request.POST)
		if signupform.is_valid():
			if not User.objects.filter(username=signupform.cleaned_data['handle']).count():
				u = User(
						username=signupform.cleaned_data['handle'],
						email=signupform.cleaned_data['email'],
						first_name=signupform.cleaned_data['first_name'],
						last_name=signupform.cleaned_data['last_name'],
					)
				u.set_unusable_password()
				u.save()
				try:
					if settings.JOUST_SMS_NOTIFICATIONS == True:
						p = u.get_profile()
						p.phone_number = signupform.cleaned_data['phone_number']
				except:
					pass
				login(request, u)
				return redirect('joust-selfserve-tournament')
			else:
				signupform._errors['handle'] = _(u'This handle has been taken.')
				
	#generate blank form
	else:
		signupform = forms.UserSignupForm()
		
	return render_to_response('joust/self-service/signup.html', {'signupform':signupform}, 
								context_instance=RequestContext(request))
Example #6
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 #7
0
        def authenticate(self, username=None, password=None):

            try:
                userinfo = authenticate(username=username, password=password)

                # prefix 'p2p' to the username so it doesn't collide with
                # any other local users. This doesn't change the username
                # that you use for authentication
                local_username = '******'.join(('p2p', userinfo['username']))

                try:
                    user = User.objects.get(username=local_username)

                except User.DoesNotExist, e:
                    user = User(
                        username=local_username,
                        email=userinfo['email'],
                        first_name=userinfo['first_name'],
                        last_name=userinfo['last_name'])
                    user.set_unusable_password()
                    user.is_staff = True
                    user.is_superuser = True
                    user.save()

                return user
    def authenticate(self, ticket, service):
        """Verifies CAS ticket and gets or creates User object"""
        logger.info('Authenticating against CAS: service = %s ; ticket = %s', service, ticket)
        usernames = self._verify_cas1(ticket, service)
        if not usernames:
            return None
        users = list(User.objects.filter(username__in=usernames))
        logger.info('Authentication turned up %s users: %s', len(users), users)
        if users:
            user = users[0]
            logger.info('Picking primary user: %s', user)
        else:
            logger.info('Creating new user for %s', usernames[0])
            user = User(username=usernames[0])
            user.set_unusable_password()
            user.save()

        if len(users) > 1:
            logger.info('Sending merge signal for other users: %s', users[1:])
            try:
                result = signals.on_cas_merge_users.send(sender=self, primary=user, others=users[1:])
            except Exception:
                logger.exception('Merge signal failed!')
            else:
                logger.info('Sent merge signal. Result: %s', result)

        logger.info('Authenticated user: %s' % user)
        signals.on_cas_authentication.send(sender=self, user=user)
        return user
    def handle(self, *args, **options):
        print "Reading users from stdin..."
        usernames = sys.stdin.read().split()
        users_created_count = 0
        verbosity = int(options.get("verbosity", "1"))
        emailsuffix = options["emailsuffix"]

        for username in usernames:
            try:
                User.objects.get(username=username)
            except User.DoesNotExist:
                email = None
                if emailsuffix != None:
                    try:
                        email = emailsuffix.format(username=username)
                    except KeyError:
                        print "Error: emailsuffix must contain '{username}'"
                        sys.exit()
                user = User(username=username, email=email)
                print "Create user:%s with email %s" % (username, email)
                user.set_unusable_password()
                self.save_user(user, verbosity)
                users_created_count += 1
        if verbosity > 0:
            print "Added %d users." % users_created_count
            print "%s users already existed." % (len(usernames) - users_created_count)
Example #10
0
    def create_user(self, request, access, token, user_data):
        identifier = self.identifier_from_data(user_data)
        username = hashlib.sha224(str(identifier)).hexdigest()[:30]
        if User.objects.filter(username=username).count():
            logger.warning("DefaultFacebookCallback.create_user: A user for" \
                    "was already found, when asked to create a user for %s"
                    % username)
            user = User.objects.get(username=username)
        else:
            user = User(username=username)
            user.set_unusable_password()
            logger.debug(user_data)
            if 'email' in user_data:
                user.email = user_data["email"]
            if 'first_name' in user_data:
                user.first_name = user_data['first_name']
            if 'last_name' in user_data:
                user.last_name = user_data['last_name']
            user.save()
            logger.debug("DefaultFacebookCallback.create_user: new django" \
                    "user created for %s" % username)

        self.create_profile(request, access, token, user)
        self.handle_unauthenticated_user(request, user ,access, token, user_data)
        return user
Example #11
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 #12
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 #13
0
def facebook_login(request, redirect_url=None, template_name='facebook/login.html'):
    """
    Log in a facebook user

    Usually handles the django side of what happens when you click the
    facebook connect button. The user will get redirected to the 'setup' view
    if thier facebook account is not on file. If the user is on file, they
    will get redirected. You can specify the redirect url in the following
    order of precedence:

        1.  whatever url is in the 'next' get parameter passed to the
            facebook_login url 
        2.  whatever url is passed to the facebook_login view when the url 
            is defined 
        3.  whatever url is defined in the LOGIN_REDIRECT_URL setting directive

    Sending a user here without login will display a login template.

    Params: 
    
        *   redirect_url: defines where to send the user after they are
            logged in. This can get overridden by the url in the 'next' get 
            param passed on the url. 
        *   template_name: Template to use if a user arrives at this page 
            without submitting to it. Uses 'facebook/login.html' by default.
            
    """
    # determine redirect url in order of priority
    passed_redirect_url = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
    set_redirect_url = getattr(settings, "LOGIN_REDIRECT_URL", "/")
    redirect_url = redirect_url or passed_redirect_url or set_redirect_url
    
    # User is logging in
    if request.method == 'POST':
        user = authenticate(request=request)
        if user:
            if not user.is_active:
                raise FacebookAuthError('This account is disabled.')            
            login(request, user)
            return HttpResponseRedirect(redirect_url)
        elif request.facebook.uid:
            # created profile object and dummy django user
            profile = FacebookProfile(facebook_id=request.facebook.uid)
            user = User(username=request.facebook.uid, email=profile.email, 
                first_name=profile.first_name, last_name=profile.last_name)
            user.set_unusable_password()
            user.save()
            profile.user = user
            profile.save()
            user = authenticate(request=request)
            login(request, user)
            return HttpResponseRedirect(redirect_url)
            
    # User is already logged in
    elif request.user.is_authenticated():
        return HttpResponseRedirect(redirect_url)

    return render_to_response(template_name, {
        REDIRECT_FIELD_NAME: redirect_url
    }, context_instance=RequestContext(request))
Example #14
0
def fb_authenticate(request, json_params):
  import requests
  params = {
      "fields" : "last_name,first_name,email,username",
      "access_token" : json_params['access_token']
  }

  url = "https://graph.facebook.com/{0}".format(json_params['user_id'])
  user_request = requests.get(url, params=params)
  user_data = json.loads(user_request.text)

  if ("last_name" not in user_data or
      "first_name" not in user_data or
      "email" not in user_data or
      "username" not in user_data):
    return HttpResponseUnauthorized('access-token')

  user_to_auth = None
  try:
    user_to_auth = FbUser.objects.get(fb_user_id=json_params['user_id']).user
  except ObjectDoesNotExist:
    user_to_auth = User(username=user_data['username'],
                first_name=user_data['first_name'],
                last_name=user_data['last_name'],
                email=user_data['email'])
    user_to_auth.set_unusable_password()
    user_to_auth.save()
    FbUser(user=user_to_auth, fb_user_id=json_params['user_id']).save()

  return generate_ticket_response(user_to_auth)
Example #15
0
def google_return (request, url=None):
    from django.contrib.auth import login
    good = False
    # ocdir.clean_gkeys()
     
    email = request.REQUEST.get('openid.ext1.value.email', '')
    handle = request.REQUEST.get('openid.assoc_handle', '')
    mode = request.REQUEST.get('openid.mode', '')
    if handle != '' and email != '' and mode == 'id_res':
        u = User.objects.filter(email=email)
        if not u:
            u = User(email=email,username=email.split("@")[0])
            u.save()
            u.set_unusable_password()
        u = User.objects.get(email=email)
        u.backend='django.contrib.auth.backends.ModelBackend'
        login(request,u)
        good = True
        x = request.user

    if not url.startswith("http://"):
        url = url.replace("http:/", "http://")

    if not re.search("http://", url):
        url = "http://" + url

    if good:
        return HttpResponseRedirect(url)
    if not "?" in url:
        url += "?"
    url += '&message='
    url += urllib.quote("Invalid Google login, please try again.")

    return HttpResponseRedirect(url)
Example #16
0
    def authenticate(self, username=None, password=None):
        """
        Checks if a given user and password can connect to campusnet.
        """

        try:
            login_valid = auth.authenticate(username, password)
        except:
            return None

        if not login_valid:
            return None

        if login_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='******')
                user.set_unusable_password()
                user.save()
            return user
        return None
    def handle(self, *args, **options):
        self.inputencoding = options['inputencoding']
        if len(args) != 1:
            raise CommandError('Username is required. See --help.')
        verbosity = int(options.get('verbosity', '1'))
        username = args[0]
        kw = {}
        for attrname in ('email', 'is_superuser'):
            kw[attrname] = options[attrname]
        if options['is_superuser']:
            kw['is_staff'] = True

        if User.objects.filter(username=username).count() == 0:
            user = User(username=username, **kw)
            if options['password']:
                user.set_password(options['password'])
            else:
                user.set_unusable_password()
            self.save_user(user, verbosity)

            profile = user.devilryuserprofile
            full_name = options.get('full_name')
            if full_name:
                profile.full_name = unicode(full_name, self.inputencoding)
            self.save_profile(profile)
        else:
            raise CommandError('User "{0}" already exists.'.format(username))
Example #18
0
    def authenticate(self, token=None):        
        try:
            try:
                #not first time login, assume not deauth
                u = Person.objects.get(access_token=token)                                
            except Person.DoesNotExist:                
                profile = facebook.GraphAPI(token).get_object("me")
                uid = profile['id']

                try:
                    #login first time but face already exist
                    u = Person.objects.get(uid=uid)                     
                    u.access_token=token
                    #u.user.email=profile['email']
                    u.user.save()                    
                    u.save()
                except Person.DoesNotExist:
                    #login first time and face does not exist
                    u = Person(uid=uid,access_token=token,profile_url=profile['link'])
                    user = User(username=uid,first_name=profile['first_name'],last_name=profile['last_name'])            
                    user.set_unusable_password()
                    user.save()
                    u.user=user
                    u.save()                                          
            return u.user
        except:
            return None
Example #19
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 #20
0
        def authenticate(self, username=None, password=None):

            try:
                userinfo = authenticate(username=username, password=password)

                # prefix 'p2p' to the username so it doesn't collide with
                # any other local users. This doesn't change the username
                # that you use for authentication
                local_username = "******".join(("p2p", userinfo["username"]))

                try:
                    user = User.objects.get(username=local_username)

                except User.DoesNotExist:
                    user = User(
                        username=local_username,
                        email=userinfo["email"],
                        first_name=userinfo["first_name"],
                        last_name=userinfo["last_name"],
                    )
                    user.set_unusable_password()
                    user.is_staff = True
                    user.is_superuser = True
                    user.save()

                return user
            except P2PAuthError:
                pass

            return None
Example #21
0
    def authenticate(self, profile):
        # django.contrib.auth.models.User.username is required and 
        # has a max_length of 30 so to ensure that we don't go over 
        # 30 characters we url-safe base64 encode the sha1 of the identifier 
        # returned from janrain and slice `=` from the end.
        hashed_user = safe_encode(sha1(profile['identifier']).digest())[:-1]
        try :
            u = User.objects.get(username=hashed_user)
        except User.DoesNotExist:

            fn, ln = self.get_name_from_profile(profile)
            u = User(
                    username=hashed_user,
                    password='',
                    first_name=fn,
                    last_name=ln,
                    email=self.get_email(profile)
                )
            # Set an unusable password to protect unauthorized access.
            u.set_unusable_password()
            u.is_active = True
            u.is_staff = False
            u.is_superuser = False
            u.save()
        return u
Example #22
0
def load_json_user(json):
    """
    Given a JSON string, returns a Django User instance.
    """
    data = simplejson.loads(json)
    try:
        user = User.objects.get(username=data['username'])
    except User.DoesNotExist:
        user = User()
    
    for key in SIMPLE_KEYS:
        setattr(user, key, data[key])
    user.set_unusable_password()
    user.save()
    
    ctype_cache = {}
    
    permissions = []
    
    for perm in data['permissions']:
        ctype = ctype_cache.get(perm['content_type'], None)
        if not ctype:
            try:
                ctype = ContentType.objects.get_by_natural_key(perm['content_type'])
            except ContentType.DoesNotExist:
                continue
            ctype_cache[perm['content_type']] = ctype
        try:
            permission = Permission.objects.get(content_type=ctype, codename=perm['codename'])
        except Permission.DoesNotExist:
            continue
        permissions.append(permission)
    
    user.user_permissions = permissions
    return user
Example #23
0
def create_user(username, email_id="", password=None, first_name="", last_name=""):
    """ This function called for new user sign up on p. interface. Thus username should be a valid phone number."""
    usr = None
    profile = None
    if not username:
        return usr, profile
    username = username.strip()
    is_type = "id"
    if is_valid_mobile(username):
        is_type = "mobile"
        try:
            usr = User(username=username, email="")
            if password is None or password == "":
                # use set_unusable_password to allow user to set his password in future
                usr.set_unusable_password()
            else:
                usr.set_password(password)
            if first_name:
                usr.first_name = first_name
            if last_name:
                usr.last_name = last_name
            usr.save()
            profile = Profile(
                user=usr, created_on=datetime.now(), primary_phone="", primary_email="", secondary_email=""
            )
            if first_name and last_name:
                profile.full_name = "%s %s" % (first_name, last_name)
            profile.save()
            phone = Phone(user=profile, phone=username, type="primary")
            phone.is_verified = True
            phone.verified_on = datetime.now()
            phone.save()
        except Exception, e:
            log.exception("Error create_user username: %s  Exception: %s" % (username, repr(e)))
            return None, None
Example #24
0
 def create_user(self, commit=True):
     user = User()
     # data collected by providers, if any, is passed as `initial`
     # signup form data. This may contain fields such as
     # `first_name`, whereas these may not have field counterparts
     # in the form itself. So let's pick these up here...
     data = self.initial
     user.last_name = data.get('last_name', '')
     user.first_name = data.get('first_name', '')
     if app_settings.USERNAME_REQUIRED:
         user.username = self.cleaned_data["username"]
     else:
         while True:
             user.username = self.random_username()
             try:
                 User.objects.get(username=user.username)
             except User.DoesNotExist:
                 break
     user.email = self.cleaned_data["email"].strip().lower()
     # @TODO this is MRA specific hack!!
     user.username = user.email
     user.set_unusable_password()
     if commit:
         user.save()
     return user
Example #25
0
    def _clean_add_user(self):
        """run in clean() so we can process users after course is created
        from course-string
        """
        usernames = self.cleaned_data['add_user']
        if not usernames:
            return

        # take it from here, in case instance is not yet created
        group = self.cleaned_data['group']
        for line in usernames.split('\n'):
            clean_line = line.strip().rstrip().split(':')
            username = clean_line[0]
            password = clean_line[1] if len(clean_line) > 1 else False
            also_faculty = False
            if username.startswith('*'):
                username = username[1:]
                also_faculty = True
            if username:
                try:
                    user = User.objects.get(username=username)
                except User.DoesNotExist:
                    user = User(username=username)
                    if password:
                        user.set_password(password)
                    else:
                        user.set_unusable_password()
                    user.save()
                user.groups.add(group)
                if also_faculty and self.cleaned_data['faculty_group']:
                    user.groups.add(self.cleaned_data['faculty_group'])
        return usernames
Example #26
0
 def authenticate(self, username, password, ):
     (result,) = query(1, "AUTHENTICATE", username, password, )
     print result
     if result == 'true':
         try:
             user = User.objects.get(username=username)
             if len(user.groups.filter(name='local-auth-only')) > 0:
                 if user.check_password(password):
                     return user
                 else:
                     return None
             else:
                 return user
         except User.DoesNotExist:
             user = User(username=username)
             user.set_unusable_password()
             user.is_staff = False
             user.is_superuser = False
             # Is there a race condition here? Yes.
             # Should I do more error-checking? Yes.
             # Do I care? No.
             (first, last, email,) = query(3, 'FINGER', username)
             user.first_name = first
             user.last_name = last
             user.email = email
             user.save()
             try:
                 user.groups.add(auth.models.Group.objects.get(name='autocreated'))
             except ObjectDoesNotExist:
                 print "Failed to retrieve autocreated group"
             return user
     return None
Example #27
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
Example #28
0
def make_and_login_participant(id_string, request):
    """ If there is a participant with this id_string, log them in. If
    not, create one and log them in.  See:
    http://stackoverflow.com/questions/3222549/
       how-to-automatically-login-a-user-after-registration-in-django
    """
    # you'd better check before invoking this function.
    assert request.user.is_staff
    participant = get_object_or_404(Participant, id_string=id_string)
    if not participant.user:
        assert participant.user is None  # do not mock this line.
        new_user = User()
        new_user.set_unusable_password()
        new_user.username = id_string
        new_user.save()
        participant.user = new_user
        participant.save()
    participant.user.backend = 'django.contrib.auth.backends.ModelBackend'
    assert participant.user is not None
    messages.info(request, "Logged in!")
    authenticate(
        username=participant.user.username,
        password=participant.user.password)
    login(request, participant.user)
    return participant
Example #29
0
 def build_user(self, user_data):
     extra_data = user_data.pop('extra_data')
     cloud_id = extra_data['cloud_id']
     try:
         account = AldrynCloudUser.objects.get(cloud_id=cloud_id)
     except AldrynCloudUser.DoesNotExist:
         username = user_data.pop('username')
         email = user_data.pop('email')
         try:
             user = User.objects.get(username=username)
         except User.DoesNotExist:
             user = User(username=username, email=email)
             user.save()
         else:
             # User with this username already exists. Checking if the emails
             # matches, otherwise creating a new user.
             if user.email != email:
                 free_username = self._get_free_username(username)
                 user = User(username=free_username, email=email)
         account = AldrynCloudUser(cloud_id=cloud_id, user=user)
         account.save()
     else:
         user = account.user
     for key, value in user_data.items():
         setattr(user, key, value)
     user.set_unusable_password()
     user.save()
     return user
Example #30
0
File: main.py Project: WISVCH/szp4
    def run(self, args):
        team = Team()
        team.name = args.name
        team.organisation = args.organisation
        team.teamclass = Teamclass.objects.get(rank=args.teamclass)
        team.location = args.location
        team.save()
        Contest.objects.get().save()  # Updates 'resulttime'
        if args.ip or args.password:
            if args.password:
                user = User(username=team.name.replace(' ', '_'))
                user.set_password(args.password)
            else:
                user = User(username=args.ip.replace('.', '_'))
                user.set_unusable_password()
            user.save()

            profile = Profile()
            profile.is_judge = False
            profile.user = user
            profile.team = team
            if args.ip:
                profile.ip_address = socket.gethostbyname(args.ip)
            profile.save()
        else:
            print "Team '%s' has id %d" % (team.name, team.id)
Example #31
0
def facebook_login(request,
                   redirect_url="/",
                   template_name='facebook/login.html',
                   extra_context=None):
    """
    facebook_login
    ===============================
    
    Handles logging in a facebook user. Usually handles the django side of
    what happens when you click the facebook connect button. The user will get
    redirected to the 'setup' view if thier facebook account is not on file.
    If the user is on file, they will get redirected. You can specify the
    redirect url in the following order of presidence:
    
     1. whatever url is in the 'next' get parameter passed to the facebook_login url
     2. whatever url is passed to the facebook_login view when the url is defined
     3. whatever url is defined in the LOGIN_REDIRECT_URL setting directive
    
    Sending a user here without login will display a login template.
    
    If you define a url to use this view, you can pass the following parameters:
     * redirect_url: defines where to send the user after they are logged in. This
                     can get overridden by the url in the 'next' get param passed on 
                     the url.
     * template_name: Template to use if a user arrives at this page without submitting
                      to it. Uses 'facebook/login.html' by default.
     * extra_context: A context object whose contents will be passed to the template.
    """
    # User is logging in
    if request.method == "POST":
        log.debug("OK logging in...")
        url = reverse('facebook_setup')
        if request.POST.get(REDIRECT_FIELD_NAME, False):
            url += "?%s=%s" % (REDIRECT_FIELD_NAME,
                               request.POST[REDIRECT_FIELD_NAME])
        elif redirect_url:
            url += "?%s=%s" % (REDIRECT_FIELD_NAME, redirect_url)
        user = authenticate(request=request)
        if user is not None:
            if user.is_active:
                login(request, user)
                # Redirect to a success page.
                log.debug("Redirecting to %s" % url)
                return HttpResponseRedirect(url)
            else:
                log.debug("This account is disabled.")
                raise FacebookAuthError('This account is disabled.')
        elif request.facebook.uid:
            if getattr(settings, "FACEBOOK_USE_DUMMY_ACCOUNT", False):
                #check that this fb user is not already in the system
                try:
                    FacebookProfile.objects.get(
                        facebook_id=request.facebook.uid)
                    # already setup, move along please
                    return HttpResponseRedirect(redirect_url)
                except FacebookProfile.DoesNotExist, e:
                    # not in the db, ok to continue
                    pass

                profile = FacebookProfile(facebook_id=request.facebook.uid)
                user = User(username=request.facebook.uid, email=profile.email)
                user.set_unusable_password()
                user.save()
                profile.user = user
                profile.save()
                log.info("Added user and profile for %s!" %
                         request.facebook.uid)
                user = authenticate(request=request)
                login(request, user)
                return HttpResponseRedirect(redirect_url)
            else:
                #we have to set this user up
                log.debug("Redirecting to setup")
                return HttpResponseRedirect(url)
Example #32
0
    def get_or_create_user(self, username, request, ldapo, userdn):
        """Get an existing user, or create one if it does not exist."""
        username = re.sub(INVALID_USERNAME_CHAR_REGEX, '', username).lower()

        try:
            user = User.objects.get(username=username)
            return user
        except User.DoesNotExist:
            try:
                import ldap

                # Perform a BASE search since we already know the DN of
                # the user
                search_result = ldapo.search_s(userdn,
                                               ldap.SCOPE_BASE)
                user_info = search_result[0][1]

                given_name_attr = getattr(
                    settings, 'LDAP_GIVEN_NAME_ATTRIBUTE', 'givenName')
                first_name = user_info.get(given_name_attr, [username])[0]

                surname_attr = getattr(
                    settings, 'LDAP_SURNAME_ATTRIBUTE', 'sn')
                last_name = user_info.get(surname_attr, [''])[0]

                # If a single ldap attribute is used to hold the full name of
                # a user, split it into two parts.  Where to split was a coin
                # toss and I went with a left split for the first name and
                # dumped the remainder into the last name field.  The system
                # admin can handle the corner cases.
                try:
                    if settings.LDAP_FULL_NAME_ATTRIBUTE:
                        full_name = \
                            user_info[settings.LDAP_FULL_NAME_ATTRIBUTE][0]
                        full_name = full_name.decode('utf-8')
                        first_name, last_name = full_name.split(' ', 1)
                except AttributeError:
                    pass

                if settings.LDAP_EMAIL_DOMAIN:
                    email = '%s@%s' % (username, settings.LDAP_EMAIL_DOMAIN)
                elif settings.LDAP_EMAIL_ATTRIBUTE:
                    try:
                        email = user_info[settings.LDAP_EMAIL_ATTRIBUTE][0]
                    except KeyError:
                        logging.error('LDAP: could not get e-mail address for '
                                      'user %s using attribute %s',
                                      username, settings.LDAP_EMAIL_ATTRIBUTE)
                        email = ''
                else:
                    logging.warning(
                        'LDAP: e-mail for user %s is not specified',
                        username)
                    email = ''

                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 ImportError:
                pass
            except ldap.INVALID_CREDENTIALS:
                # FIXME I'd really like to warn the user that their
                # ANON_BIND_UID and ANON_BIND_PASSWD are wrong, but I don't
                # know how
                pass
            except ldap.NO_SUCH_OBJECT as e:
                logging.warning("LDAP error: %s settings.LDAP_BASE_DN: %s "
                                "User DN: %s",
                                e, settings.LDAP_BASE_DN, userdn,
                                exc_info=1)
            except ldap.LDAPError as e:
                logging.warning("LDAP error: %s", e, exc_info=1)

        return None
Example #33
0
def get_and_update_user(user_info):
    username = convert_sls_uuid(user_info['sub'])
    try:
        user = User.objects.get(username=username)
        if not user.first_name:
            user.first_name = user_info['given_name']
        if not user.last_name:
            user.last_name = user_info['family_name']
        if not user.email:
            user.email = user_info['email']
        user.save()
    except User.DoesNotExist:
        # Create a new user. Note that we can set password
        # to anything, because it won't be checked.
        user = User(username=username,
                    password='',
                    first_name=user_info['given_name'],
                    last_name=user_info['family_name'],
                    email=user_info['email'])
        user.set_unusable_password()
        user.save()
    UserProfile.objects.get_or_create(user=user, user_type='BEN')
    group = Group.objects.get(name='BlueButton')
    user.groups.add(group)
    # Log in the user
    user.backend = 'django.contrib.auth.backends.ModelBackend'

    # Determine patient_id
    fhir_source = get_resourcerouter()
    crosswalk, _ = Crosswalk.objects.get_or_create(user=user,
                                                   fhir_source=fhir_source)
    hicn = user_info.get('hicn', "")
    crosswalk.user_id_hash = hicn
    crosswalk.save()

    auth_state = FhirServerAuth(None)
    certs = (auth_state['cert_file'], auth_state['key_file'])

    # URL for patient ID.
    url = fhir_source.fhir_url + \
        "Patient/?identifier=http%3A%2F%2Fbluebutton.cms.hhs.gov%2Fidentifier%23hicnHash%7C" + \
        crosswalk.user_id_hash + \
        "&_format=json"
    response = requests.get(url, cert=certs, verify=False)
    backend_data = response.json()

    if 'entry' in backend_data and backend_data['total'] == 1:
        fhir_id = backend_data['entry'][0]['resource']['id']
        crosswalk.fhir_id = fhir_id
        crosswalk.save()

        logger.info("Success:Beneficiary connected to FHIR")
    else:
        logger.error("Failed to connect Beneficiary " "to FHIR")

    # Get first and last name from FHIR if not in OIDC Userinfo response.
    if user_info['given_name'] == "" or user_info['family_name'] == "":
        if 'entry' in backend_data:
            if 'name' in backend_data['entry'][0]['resource']:
                names = backend_data['entry'][0]['resource']['name']
                first_name = ""
                last_name = ""
                for n in names:
                    if n['use'] == 'usual':
                        last_name = n['family']
                        first_name = n['given'][0]
                    if last_name or first_name:
                        user.first_name = first_name
                        user.last_name = last_name
                        user.save()

    return user
Example #34
0
    def get_or_create_user(self, username, request=None, ldapo=None,
                           userdn=None):
        """Return a user account, importing from LDAP if necessary.

        If the user already exists in the database, it will be returned
        directly. Otherwise, this will attempt to look up the user in LDAP
        and create a local user account representing that user.

        Args:
            username (unicode):
                The username to look up.

            request (django.http.HttpRequest, optional):
                The optional HTTP request for this operation.

            ldapo (ldap.LDAPObject, optional):
                The existing LDAP connection, if the caller has one. If not
                provided, a new connection will be created.

            userdn (unicode, optional):
                The DN for the user being looked up, if the caller knows it.
                If not provided, the DN will be looked up.

        Returns:
            django.contrib.auth.models.User:
            The resulting user, if it could be found either locally or in
            LDAP. If the user does not exist, ``None`` is returned.
        """
        username = self.INVALID_USERNAME_CHAR_REGEX.sub('', username).lower()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            # The user wasn't in the database, so we'll look it up in
            # LDAP below.
            pass

        if ldap is None:
            logging.error('Attempted to look up user "%s" in LDAP, but the '
                          'python-ldap package is not installed!',
                          username)
            return None

        try:
            if ldapo is None:
                ldapo = self._connect(request=request)

                if ldapo is None:
                    return None

            if userdn is None:
                userdn = self._get_user_dn(ldapo=ldapo,
                                           username=username,
                                           request=request)

                if userdn is None:
                    return None

            # Perform a BASE search since we already know the DN of
            # the user
            search_result = ldapo.search_s(userdn, ldap.SCOPE_BASE)
            user_info = search_result[0][1]

            given_name_attr = getattr(settings, 'LDAP_GIVEN_NAME_ATTRIBUTE',
                                      'givenName')
            first_name = user_info.get(given_name_attr, [username])[0]

            surname_attr = getattr(settings, 'LDAP_SURNAME_ATTRIBUTE', 'sn')
            last_name = user_info.get(surname_attr, [''])[0]

            # If a single ldap attribute is used to hold the full name of
            # a user, split it into two parts.  Where to split was a coin
            # toss and I went with a left split for the first name and
            # dumped the remainder into the last name field.  The system
            # admin can handle the corner cases.
            #
            # If the full name has no white space to split on, then the
            # entire full name is dumped into the first name and the
            # last name becomes an empty string.
            try:
                if settings.LDAP_FULL_NAME_ATTRIBUTE:
                    full_name = force_text(
                        user_info[settings.LDAP_FULL_NAME_ATTRIBUTE][0])

                    try:
                        first_name, last_name = full_name.split(' ', 1)
                    except ValueError:
                        first_name = full_name
                        last_name = ''

            except AttributeError:
                pass

            if settings.LDAP_EMAIL_DOMAIN:
                email = '%s@%s' % (username, settings.LDAP_EMAIL_DOMAIN)
            elif settings.LDAP_EMAIL_ATTRIBUTE:
                try:
                    email = user_info[settings.LDAP_EMAIL_ATTRIBUTE][0]
                except KeyError:
                    logging.error('LDAP: could not get e-mail address for '
                                  'user %s using attribute %s',
                                  username, settings.LDAP_EMAIL_ATTRIBUTE)
                    email = ''
            else:
                logging.warning(
                    'LDAP: e-mail for user %s is not specified',
                    username)
                email = ''

            user = User(username=username,
                        password='',
                        first_name=first_name,
                        last_name=last_name,
                        email=email)
            user.set_unusable_password()
            user.save()

            return user
        except ldap.NO_SUCH_OBJECT as e:
            logging.warning("LDAP error: %s settings.LDAP_BASE_DN: %s "
                            "User DN: %s",
                            e, settings.LDAP_BASE_DN, userdn,
                            exc_info=1)
        except ldap.LDAPError as e:
            logging.warning("LDAP error: %s", e, exc_info=1)

        return None
            counter += 1

        names = old_comment['Name'].split(None, 1)
        first_name = names[0]
        if len(names) > 1:
            last_name = names[1]
        else:
            last_name = ''

        user = User(
            username=trial_username,
            first_name=first_name[:30],
            last_name=last_name[:30],
            email=old_comment['Email'],
            password='',
        )
        user.set_unusable_password()
        user.save()

    comment = Comment(
        content_type=ContentType.objects.get_for_model(member),
        object_id=member.id,
        user=user,
        status='approved',
        title=comment_title.strip(),
        comment=comment_content.strip(),
        submit_date=old_comment['Date'],
        ip_address=old_comment['IPAddress'],
    )
    comment.save()
Example #36
0
class ShibbolethTest(TestCase):
    def setUp(self):
        self.user = User(
            username='******',
            email='*****@*****.**',
            first_name='Matti',
            last_name='Sukunimi',
        )
        self.user.set_unusable_password()
        self.user.save()
        self.user.userprofile.student_id = '000'
        self.user.userprofile.organization = 'first.invalid'
        self.user.userprofile.save()

        self.login_url = reverse('shibboleth-login')

    def test_permission_is_denied_when_user_id_is_missing(self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_eppn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def test_permission_is_denied_when_user_id_does_not_contain_domain(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = 'invalid-non-domain'
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def test_permission_is_denied_when_user_id_is_way_too_long(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = '-'.join(['invalid'] * 1000) + '@first.invalid'
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def test_new_user_is_create_when_there_is_valid_data(self):
        meta = DEF_SHIBD_META.copy()
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_new_user_is_create_with_tuni_user_info(self):
        """
        Validate that shib login works with data obtained from Tampere universities
        """
        env_vars = ENV_VARS.copy()
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_schacPersonalUniqueCode'] = (
            'urn:schac:personalUniqueCode:int:studentID:uta.fi:A11111;'
            'urn:schac:personalUniqueCode:int:studentID:tamk.fi:222222;'
            'urn:schac:personalUniqueCode:int:studentID:tut.fi:333333;'
            'urn:schac:personalUniqueCode:int:studentID:uta.fi:44444')
        tests = [
            ('uta.fi', 'A11111'),  # first instance is selected
            ('tamk.fi', '222222'),
            ('tut.fi', '333333'),
        ]
        for domain, studentid in tests:
            with self.subTest(domain=domain, studentid=studentid):
                env_vars['STUDENT_DOMAIN'] = domain
                meta['TESTSHIB_schacHomeOrganization'] = domain
                with override_settings(SHIBBOLETH_ENVIRONMENT_VARS=env_vars):
                    response = self._get(meta)
                self.assertEqual(response.status_code, 302)
                self.assertEqual(User.objects.count(), 2)
                user = User.objects.get(username='******')
                self.assertEqual(user.userprofile.student_id, studentid)

    def test_new_user_is_create_even_with_lowercase_meta(self):
        meta = {k.lower(): v for k, v in DEF_SHIBD_META.items()}
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_email_is_create_when_when_email_is_missing(self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_mail']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '{:d}@localhost'.format(user.id))
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')

    def test_cn_is_used_for_first_and_last_name_when_givename_and_sn_are_missing(
            self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_givenName']
        del meta['TESTSHIB_sn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Temppu')
        self.assertEqual(user.last_name, 'Ojanen Teettari')

    def test_cn_is_used_for_first_name_when_givename_is_missing(self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_givenName']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Temppu')
        self.assertEqual(user.last_name, 'Teekkari')

    def test_displayname_is_used_for_first_name_when_givename_and_cn_are_missing(
            self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_givenName']
        del meta['TESTSHIB_cn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.first_name, 'Teemudemus')
        self.assertEqual(user.last_name, 'Teekkari')

    def test_no_student_id_is_set_when_it_is_missing_from_shib(self):
        meta = DEF_SHIBD_META.copy()
        del meta['TESTSHIB_schacPersonalUniqueCode']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, None)

    def test_second_domain_student_id_is_used_when_setting_is_changed(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = self.user.username
        env_vars = ENV_VARS.copy()
        env_vars['STUDENT_DOMAIN'] = 'second.invalid'
        meta['TESTSHIB_schacHomeOrganization'] = 'second.invalid'
        with override_settings(SHIBBOLETH_ENVIRONMENT_VARS=env_vars):

            response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.userprofile.student_id, 'abcdef')

    def test_last_name_is_not_updated_when_sn_is_missing(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = self.user.username
        del meta['TESTSHIB_sn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Sukunimi')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_values_are_not_updated_when_they_are_missing(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = self.user.username
        del meta['TESTSHIB_givenName']
        del meta['TESTSHIB_sn']
        del meta['TESTSHIB_schacPersonalUniqueCode']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Matti')
        self.assertEqual(user.last_name, 'Sukunimi')
        self.assertEqual(user.userprofile.student_id, '000')

    def test_unicode_values_are_supported_for_names(self):
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = self.user.username
        meta['TESTSHIB_givenName'] = 'Mänty'
        meta['TESTSHIB_sn'] = 'Hölmöläinen'
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Mänty')
        self.assertEqual(user.last_name, 'Hölmöläinen')

    @override_settings(SHIBBOLETH_LOGIN={'ALLOW_SEARCH_WITH_EMAIL': True})
    def test_old_user_found_using_email(self):
        meta = DEF_SHIBD_META.copy()
        email = self.user.email
        meta['TESTSHIB_mail'] = email
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, email)
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_permission_is_denied_when_user_is_inactive(self):
        self.user.is_active = False
        self.user.save()
        meta = DEF_SHIBD_META.copy()
        meta['TESTSHIB_eppn'] = self.user.username
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def _get(self, meta):
        meta = {key: quote(value) for key, value in meta.items()}
        return self.client.generic('GET', self.login_url, **meta)
Example #37
0
def ensure_anon_user_exists(apps, schema_editor):
    if not User.objects.filter(username=settings.ANONYMOUS_USER_NAME).exists():
        user = User(username=settings.ANONYMOUS_USER_NAME)
        user.set_unusable_password()
        user.save()
Example #38
0
    def authenticate(self, username=None, password=None):
        try:
            from pyrad import packet
            from pyrad.client import Client, Timeout
            from pyrad.dictionary import Dictionary
        except ImportError:
            return None

        if not '@' in username:
            return None

        username = username.decode('utf-8')
        password = password.decode('utf-8')
        login_user, domain = username.split('@')
        dom = UserAddresses.objects.filter(address=domain, address_type=1)

        if not dom:
            return None

        hosts = MailAuthHost.objects.filter(useraddress=dom, protocol=3)

        if not hosts:
            return None

        for host in hosts:
            if not host.split_address:
                login_user = username

            try:
                client = Client(
                    server=host.address,
                    authport=host.port,
                    secret=settings.RADIUS_SECRET[host.address].encode(
                        'utf-8'),
                    dict=Dictionary(StringIO(DICTIONARY)),
                )
            except AttributeError:
                return None

            request = client.CreateAuthPacket(
                code=packet.Accessrequestuest,
                User_Name=login_user,
            )
            request["User-Password"] = request.PwCrypt(password)
            try:
                reply = client.SendPacket(request)
            except Timeout:
                return None
            except Exception:
                return None
            if reply.code == packet.AccessReject:
                return None
            if reply.code != packet.AccessAccept:
                return None
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username)
                user.set_unusable_password()
                user.is_staff = False
                user.is_superuser = False
                if email_re.match(username):
                    user.email = username
                user.save()
            try:
                profile = user.get_profile()
            except UserProfile.DoesNotExist:
                profile = UserProfile(user=user, account_type=3)
                profile.save()
            return user
        return None
def shibboleth_session_auth(request):
    """Authenticate a session using Shibboleth.

    This allows Shibboleth to be one of many options for authenticating to
    the site. Instead of protecting the whole site via Shibboleth, we protect
    a single view (this view).  The view will authenticate the user using
    the attributes passed in via request.META to authenticate the user.

    """

    idp_attr = settings.SHIBBOLETH_SESSION_AUTH['IDP_ATTRIBUTE']
    idp = request.META.get(idp_attr)
    if not idp:
        logger.error("IdP header missing (%s)", idp_attr)
        return HttpResponseBadRequest("Invalid response from IdP")

    if idp not in settings.SHIBBOLETH_SESSION_AUTH['AUTHORIZED_IDPS']:
        logger.info("Unauthorized IdP: %s", idp)
        return HttpResponseForbidden("unauthorized IdP: {}".format(idp))

    user_attrs = {}

    for http_attr, user_attr, required in settings.SHIBBOLETH_SESSION_AUTH[
            'USER_ATTRIBUTES']:
        user_attrs[user_attr] = request.META.get(http_attr, None)
        if required and user_attrs[user_attr] is None:
            logger.error("SSO missing attribute: %s", user_attr)
            return HttpResponseBadRequest("Invalid response from IdP")

    try:
        user = User.objects.get(username=user_attrs['username'])
    except User.DoesNotExist:
        user = User(**user_attrs)
        user.set_unusable_password()
        user.save()

    idp_provided_group_names = []
    if idp in settings.SHIBBOLETH_SESSION_AUTH['GROUPS_BY_IDP']:
        for group_name in settings.SHIBBOLETH_SESSION_AUTH['GROUPS_BY_IDP'][
                idp]:
            idp_provided_group_names.append(group_name)
            try:
                group = Group.objects.get(name=group_name)
            except Group.DoesNotExist:
                logger.info(
                    "creating group %s (locally configured for IdP %s)",
                    group_name, idp)
                continue

            if group not in user.groups.all():
                user.groups.add(group)
                logger.info("adding user %s to group %s", user.username,
                            group.name)

    group_attr = settings.SHIBBOLETH_SESSION_AUTH['GROUP_ATTRIBUTE']
    if group_attr in request.META:
        idp_group_names = request.META[group_attr].split(";")
        idp_provided_group_names.extend(idp_group_names)
        for group_name in idp_group_names:
            group, created = Group.objects.get_or_create(name=group_name)
            if created:
                logging.info("creating group %s (remotely provided by IdP %s)",
                             group_name, idp)

            if group not in user.groups.all():
                group.user_set.add(user)
                logger.info("adding user %s to group %s", user.username,
                            group.name)

    user_groups = user.groups.all()
    for group in user_groups:
        if group.name not in idp_provided_group_names:
            group.user_set.remove(user)

    staff_group_name = settings.SHIBBOLETH_SESSION_AUTH['DJANGO_STAFF_GROUP']
    if staff_group_name:
        is_staff_group_member = user.groups.filter(
            name=staff_group_name).count() > 0
        if user.is_staff != is_staff_group_member:
            user.is_staff = is_staff_group_member
            user.save()

    user = authenticate(remote_user=user.username)
    login(request, user)

    if "next" in request.GET:
        redirect_target = request.GET['next']
    else:
        redirect_target = get_script_prefix()

    return HttpResponseRedirect(redirect_target)
Example #40
0
    def get_or_create_user(self, username, password):
        stripped_name = ''
        if username.lower().startswith('uid='):
            stripped_name = username.split(',')[0][4:].lower()
        try:
            user = User.objects.get(username=stripped_name)
        except User.DoesNotExist:
            try:
                l = self.bind_ldap(settings.BIND_USER, settings.BIND_PASSWORD)
                # search
                group_result = l.search_ext_s(
                    '%s,%s' % ('cn=groups', settings.SEARCH_DN),
                    ldap.SCOPE_SUBTREE, "(cn=*)", ['cn', 'memberUid'])

                result = l.search_ext_s(
                    '%s,%s' % ('cn=users', settings.SEARCH_DN),
                    ldap.SCOPE_SUBTREE, "(uid=%s)" % stripped_name,
                    settings.SEARCH_FIELDS)[0][1]
                l.unbind_s()

                membership = []
                for group in group_result:
                    if 'memberUid' in group[1] and stripped_name in group[1][
                            'memberUid']:
                        membership.append(
                            "cn=%s,cn=groups,%s" %
                            (group[1]['cn'][0], settings.SEARCH_DN))

                if len(membership) == 0:
                    membership = None

                # get email
                if 'mail' in result:
                    mail = result['mail'][0]
                else:
                    mail = ''
                # get surname
                if 'sn' in result:
                    last_name = result['sn'][0]
                else:
                    last_name = None

                # get display name
                if 'givenName' in result:
                    first_name = result['givenName'][0]
                else:
                    first_name = None
                user = User(username=stripped_name,
                            first_name=first_name,
                            last_name=last_name,
                            email=mail)
            except Exception as e:
                return None

            user.is_staff = False
            user.is_superuser = False
            user.set_unusable_password()
            user.save()
            self.set_memberships_from_ldap(user, membership)

        return user
Example #41
0
def auth(request):
    CLIENT_ID = '583451575044-i4kah52p22nlhsv1e6nstfknr1sa1qod.apps.googleusercontent.com'
    token = request.data['token']
    try:
        final = id_token.verify_oauth2_token(token, requests.Request(),
                                             CLIENT_ID)
    except ValueError:
        return Response({'error': "Wrong Token"},
                        status=status.HTTP_400_BAD_REQUEST)
    email = final.get('email', '')
    try:
        usr = User.objects.get(email__exact=email)
        usr.first_name = final.get('given_name', '')
        usr.last_name = final.get('family_name', '')
        usr.save()
        user_profile = UserExtension.objects.get(user=usr)
        # This is done to improve the photo quality from s96 to s 400.
        profile_photo_url = final.get('picture')
        index_s96 = profile_photo_url.find('s96')
        updated_profile_photo_url = profile_photo_url[:
                                                      index_s96] + "s400" + profile_photo_url[
                                                          index_s96 + 3:]
        user_profile.profile_photo = updated_profile_photo_url
        user_profile.save()
        token_value, _ = Token.objects.get_or_create(user=usr)
        final_token = str(token_value)
        return Response({'token': final_token}, status=status.HTTP_200_OK)
    except User.DoesNotExist:
        parts = email.split('@')
        if parts[1] == "iitbhu.ac.in" or parts[1] == "itbhu.ac.in":
            pass
        else:
            return Response(
                {'error': "Wrong email used, login with @itbhu.ac.in only!"},
                status=status.HTTP_400_BAD_REQUEST)
        new = User()
        new.email = email
        new.username = parts[0]
        new.first_name = final.get('given_name', '')
        new.last_name = final.get('family_name', '')
        new.set_unusable_password()
        new.is_staff = False
        new.is_superuser = False
        new.is_active = True
        new.save()
        Token.objects.create(user=new)
        token_value, _ = Token.objects.get_or_create(user=new)
        user_profile = UserExtension()
        user_profile.user = new
        user_profile.bio = ''
        user_profile.batch = parts[0].split('.')[-1]
        # This is done to improve the photo quality from s96 to s 400.
        profile_photo_url = final.get('picture')
        index_s96 = profile_photo_url.find('s96')
        updated_profile_photo_url = profile_photo_url[:
                                                      index_s96] + "s400" + profile_photo_url[
                                                          index_s96 + 3:]
        user_profile.profile_photo = updated_profile_photo_url
        user_profile.bio = "No Bio Added"
        user_profile.save()
        final_token = str(token_value)
        return Response({'token': final_token}, status=status.HTTP_200_OK)
Example #42
0
def sync_unix_users_and_groups(min_uid, max_uid, min_gid, max_gid,
                               check_shell):
    """
  Syncs the Hue database with the underlying Unix system, by importing users and
  groups from 'getent passwd' and 'getent groups'. This should also pull in
  users who are accessible via NSS.
  """
    global __users_lock, __groups_lock

    hadoop_groups = dict((group.gr_name, group) for group in grp.getgrall() \
        if (group.gr_gid >= min_gid and group.gr_gid < max_gid) or group.gr_name == 'hadoop')
    user_groups = dict()

    __users_lock.acquire()
    __groups_lock.acquire()
    # Import groups
    for name, group in hadoop_groups.iteritems():
        try:
            if len(group.gr_mem) != 0:
                hue_group = Group.objects.get(name=name)
        except Group.DoesNotExist:
            hue_group = Group(name=name)
            hue_group.save()
            LOG.info("Created group %s" % (hue_group.name, ))

        # Build a map of user to groups that the user is a member of
        members = group.gr_mem
        for member in members:
            if member not in user_groups:
                user_groups[member] = [hue_group]
            else:
                user_groups[member].append(hue_group)

    # Now let's import the users
    hadoop_users = dict((user.pw_name, user) for user in pwd.getpwall() \
        if (user.pw_uid >= min_uid and user.pw_uid < max_uid) or user.pw_name in grp.getgrnam('hadoop').gr_mem)
    for username, user in hadoop_users.iteritems():
        try:
            if check_shell:
                pw_shell = user.pw_shell
                if subprocess.call([pw_shell, "-c", "echo"],
                                   stdout=subprocess.PIPE) != 0:
                    continue
            hue_user = User.objects.get(username=username)
        except User.DoesNotExist:
            hue_user = User(username=username,
                            password='******',
                            is_active=True,
                            is_superuser=False)
            hue_user.set_unusable_password()

        # We have to do a save here, because the user needs to exist before we can
        # access the associated list of groups
        hue_user.save()
        if username not in user_groups:
            hue_user.groups = []
        else:
            # Here's where that user to group map we built comes in handy
            hue_user.groups = user_groups[username]
        hue_user.save()
        LOG.info(_("Synced user %s from Unix") % hue_user.username)

    __users_lock.release()
    __groups_lock.release()
Example #43
0
    def get_or_create_user(self, username):
        username = username.strip()

        try:
            user = User.objects.get(username=username)
            return user
        except User.DoesNotExist:
            try:
                import ldap
                ldapo = ldap.initialize(settings.LDAP_URI)
                ldapo.set_option(ldap.OPT_REFERRALS, 0)
                ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
                if settings.LDAP_TLS:
                    ldapo.start_tls_s()
                if settings.LDAP_ANON_BIND_UID:
                    ldapo.simple_bind_s(settings.LDAP_ANON_BIND_UID,
                                        settings.LDAP_ANON_BIND_PASSWD)

                passwd = ldapo.search_s(settings.LDAP_BASE_DN,
                                        ldap.SCOPE_SUBTREE,
                                        settings.LDAP_UID_MASK % username)

                user_info = passwd[0][1]

                given_name_attr = getattr(settings,
                                          'LDAP_GIVEN_NAME_ATTRIBUTE',
                                          'givenName')
                first_name = user_info.get(given_name_attr, [username])[0]

                surname_attr = getattr(settings, 'LDAP_SURNAME_ATTRIBUTE',
                                       'sn')
                last_name = user_info.get(surname_attr, [''])[0]

                # If a single ldap attribute is used to hold the full name of
                # a user, split it into two parts.  Where to split was a coin
                # toss and I went with a left split for the first name and
                # dumped the remainder into the last name field.  The system
                # admin can handle the corner cases.
                if settings.LDAP_FULL_NAME_ATTRIBUTE:
                    full_name = user_info[settings.LDAP_FULL_NAME_ATTRIBUTE][0]
                    first_name, last_name = full_name.split(' ', 1)

                if settings.LDAP_EMAIL_DOMAIN:
                    email = u'%s@%s' % (username, settings.LDAP_EMAIL_DOMAIN)
                elif settings.LDAP_EMAIL_ATTRIBUTE:
                    email = user_info[settings.LDAP_EMAIL_ATTRIBUTE][0]
                else:
                    logging.warning("LDAP: email for user %s is not specified",
                                    username)
                    email = ''

                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 ImportError:
                pass
            except ldap.INVALID_CREDENTIALS:
                # FIXME I'd really like to warn the user that their
                # ANON_BIND_UID and ANON_BIND_PASSWD are wrong, but I don't
                # know how
                pass
            except ldap.NO_SUCH_OBJECT, e:
                logging.warning("LDAP error: %s settings.LDAP_BASE_DN: %s "
                                "settings.LDAP_UID_MASK: %s" %
                                (e, settings.LDAP_BASE_DN,
                                 settings.LDAP_UID_MASK % username))
            except ldap.LDAPError, e:
                logging.warning("LDAP error: %s" % e)
Example #44
0
def create_beneficiary_record(username=None,
                              user_hicn_hash=None,
                              user_mbi_hash=None,
                              fhir_id=None,
                              first_name="",
                              last_name="",
                              email="",
                              user_id_type="H",
                              auth_flow_dict=None):

    if auth_flow_dict is None:
        # If None, set empty dictionary.
        auth_flow_dict = {}

    if username is None:
        err_msg = "username can not be None"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    if username == "":
        err_msg = "username can not be an empty string"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    if user_hicn_hash is None:
        err_msg = "user_hicn_hash can not be None"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)
    else:
        if len(user_hicn_hash) != 64:
            err_msg = "incorrect user HICN hash format"
            log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                          fhir_id, user_mbi_hash,
                                          user_hicn_hash, err_msg)
            raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    # If mbi_hash is not NULL, perform length check.
    if user_mbi_hash is not None:
        if len(user_mbi_hash) != 64:
            err_msg = "incorrect user MBI hash format"
            log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                          fhir_id, user_mbi_hash,
                                          user_hicn_hash, err_msg)
            raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    if fhir_id is None:
        err_msg = "fhir_id can not be None"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    if fhir_id == "":
        err_msg = "fhir_id can not be an empty string"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise BBMyMedicareCallbackCrosswalkCreateException(err_msg)

    if User.objects.filter(username=username).exists():
        err_msg = "user already exists"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise ValidationError(err_msg, username)

    if Crosswalk.objects.filter(_user_id_hash=user_hicn_hash).exists():
        err_msg = "user_hicn_hash already exists"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise ValidationError(err_msg, user_hicn_hash)

    # If mbi_hash is not NULL, perform check for duplicate
    if user_mbi_hash is not None:
        if Crosswalk.objects.filter(_user_mbi_hash=user_mbi_hash).exists():
            err_msg = "user_mbi_hash already exists"
            log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                          fhir_id, user_mbi_hash,
                                          user_hicn_hash, err_msg)
            raise ValidationError(err_msg, user_hicn_hash)

    if fhir_id and Crosswalk.objects.filter(_fhir_id=fhir_id).exists():
        err_msg = "fhir_id already exists"
        log_create_beneficiary_record(auth_flow_dict, "FAIL", username,
                                      fhir_id, user_mbi_hash, user_hicn_hash,
                                      err_msg)
        raise ValidationError(err_msg, fhir_id)

    with transaction.atomic():
        user = User(username=username,
                    first_name=first_name,
                    last_name=last_name,
                    email=email)
        user.set_unusable_password()
        user.save()
        Crosswalk.objects.create(user=user,
                                 user_hicn_hash=user_hicn_hash,
                                 user_mbi_hash=user_mbi_hash,
                                 fhir_id=fhir_id,
                                 user_id_type=user_id_type)

        # Extra user information
        # TODO: remove the idea of UserProfile
        UserProfile.objects.create(user=user, user_type='BEN')
        # TODO: magic strings are bad
        group = Group.objects.get(
            name='BlueButton')  # TODO: these do not need a group
        user.groups.add(group)

        log_create_beneficiary_record(auth_flow_dict, "OK", username, fhir_id,
                                      user_mbi_hash, user_hicn_hash,
                                      "CREATE beneficiary record")
    return user
Example #45
0
def Register(request):
    try:

        reqdata = json.loads(request.body.decode('utf-8'))
        usrname = reqdata['username'] if (int(reqdata['google'])
                                          == 0) else reqdata['email']

        if (reqdata['password'] != reqdata['confirm-password']):
            data = {
                "status": 400,
                "data": {
                    "message": "Passwords did not match!"
                }
            }
            return JsonResponse(data)

        # check existing username
        if User.objects.filter(username=usrname):
            data = {
                "status": 500,
                "data": {
                    "message": "Username already exists!"
                }
            }
            return JsonResponse(data)
        # check existing email
        if User.objects.filter(email=reqdata['email']):
            data = {
                "status": 500,
                "data": {
                    "message": "Account already exists!"
                }
            }
            return JsonResponse(data)

        # create user
        if (int(reqdata['google']) == 0):
            user = User(username=usrname, email=reqdata['email'])
            user.set_password(reqdata['password'])
            user.save()
        else:
            # .split('@')[0]
            user = User(username=usrname,
                        email=reqdata['email'],
                        first_name=reqdata['first_name'],
                        last_name=reqdata['last_name'])
            user.set_unusable_password()
            user.save()

        # send welcome email
        subject, from_email, to = "Hey there - we're flipping upside down that you've joined us!", settings.EMAIL_HOST_USER, user.email
        html_content = render_to_string('email/welcome.html',
                                        {'name': user.username})
        text_content = strip_tags(html_content)
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send()

        # save user profile
        p = Profile.objects.get_or_create(user=user,
                                          latitude=reqdata['latitude'],
                                          longitude=reqdata['longitude'],
                                          device_token=reqdata['device_token'])

        if 'timezone' in reqdata:
            t = Timezones.objects.filter(tz_name=reqdata['timezone'])
            if t:
                user.profile.timezone = t[0]
                user.profile.save()

        token = Token.objects.get_or_create(user=user)

        u = {}
        u['token'] = token[0].key
        u['id'] = user.id
        u['username'] = user.username
        u['first_name'] = user.first_name
        u['last_name'] = user.last_name
        u['email'] = user.email
        u['is_staff'] = user.is_staff
        u['is_active'] = user.is_active
        u['timezone'] = None
        if user.profile.timezone:
            u['timezone'] = user.profile.timezone.tz_name

        data = {"status": 200, "data": u}
        return JsonResponse(data)
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        data = {
            "status": 500,
            "data": {
                "message": "Something went wrong!",
                "trace": str(e)
            }
        }
        return JsonResponse(data)
    def authenticate(self, username=None, password=None):

        logger = logging.getLogger('pootle.auth.ldap')

        ldo = ldap.initialize(settings.AUTH_LDAP_SERVER)
        ldo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)

        try:
            ldo.simple_bind_s(settings.AUTH_LDAP_ANON_DN,
                              settings.AUTH_LDAP_ANON_PASS)

            #            result = ldo.search_s(
            #                settings.AUTH_LDAP_BASE_DN,
            #                ldap.SCOPE_SUBTREE,
            #                (settings.AUTH_LDAP_FILTER %
            #                 ldap.filter.escape_filter_chars(username)),
            #                settings.AUTH_LDAP_FIELDS.values()
            #            )
            result = ldo.search_s(settings.AUTH_LDAP_BASE_DN,
                                  ldap.SCOPE_SUBTREE,
                                  (settings.AUTH_LDAP_FILTER % username),
                                  settings.AUTH_LDAP_FIELDS.values())

            if len(result) != 1:
                logger.debug("More or less than 1 matching account for (%s).  "
                             "Failing LDAP auth." % username)
                return None

        except ldap.INVALID_CREDENTIALS:
            logger.exception('Anonymous bind to LDAP server failed. Please '
                             'check the username and password.')
            return None
        except Exception as e:
            logger.exception('Unknown LDAP(1) error: ' + str(e))
            return None

        try:
            ldo.simple_bind_s(result[0][0], password)
            logger.debug("Successful LDAP login for user (%s)" % (username))

            try:
                user = User.objects.get(username=username)
                return user
            except User.DoesNotExist:
                logger.info("First login for LDAP user (%s). Creating new "
                            "account." % username)
                user = User(username=username, is_active=True)
                user.set_unusable_password()
                for i in settings.AUTH_LDAP_FIELDS:
                    if i != 'dn' and len(settings.AUTH_LDAP_FIELDS[i]) > 0:
                        setattr(user, i,
                                result[0][1][settings.AUTH_LDAP_FIELDS[i]][0])
                user.save()
                #                return user
                return None

        # Bad e-mail or password.
        except (ldap.INVALID_CREDENTIALS, ldap.UNWILLING_TO_PERFORM):
            logger.debug("No account or bad credentials for (%s). Failing "
                         "LDAP auth." % username)
            return None
        except Exception as e:  # No other exceptions are normal.
            logger.exception('Unknown LDAP(2) error: ' + str(e))
            raise
    def authenticate(self, credentials):         
        print "AadhaarBackendHelper.authenticate()", credentials 
        
        # Check if the user exists in the database 
        user = None 
        try: 
            user = User.objects.get(username=self._aadhaar_id)
        except: 
            pass 
        
        authenticated = False 
        try: 
            cfg = aadhaar_settings.get_cfg() 
            authenticated = self.authenticate_with_aadhaar(cfg, credentials) 
        except: 
            print "Authentication unsuccessful" 
            if user != None: 
                print "Returning without creating user" 
                # Dont create user 
                return None 

        if (user == None): 
            try: 
                if authenticated:
                    # Create the user 
                    user = User(username=self._aadhaar_id) 
                    user.set_unusable_password()
                    user.save() # This will create the profile object 
                    
                    # Update the profile 
                    profile = user.get_profile() 
                    profile.aadhaar_id = self._aadhaar_id 
                    profile.last_successful_authentication = datetime.now()
                    profile.num_successful_authentications += 1 
                    profile.save() 
                    
                    print "Created user ", user, " with profile ", profile 
                else: 
                    print "Returning without creating user" 
                    return None
            except: 
                traceback.print_exc() 
                print "Exception in AadhaarBackendHelper.authenticate()" 
                pass 
        else: 
            # user exists in the db. Authentication may have succeeded or 
            # failed. 
            print "User exists" 
            try: 
                profile = user.get_profile() 
            except: 
                # doesnt exist for some reason. Why? 
                print "Creating profile. Check why this has come here" 
                profile = AadhaarUserProfile.objects.create(user=user) 

            print "Profile before updating = ", profile.__dict__
            # Update the stats 
            if authenticated: 
                profile.last_successful_authentication = datetime.now()
                profile.num_successful_authentications += 1 
            else: 
                profile.last_unsuccessful_authentication = datetime.now()
                profile.num_unsuccessful_authentications += 1 
            profile.save() 
            print "Profile before updating = ", profile.__dict__

        # The user may exist but the authentication may have
        # failed. So we keep track of it 
        self._user = user 
        if authenticated: 
            return user 
        else: 
            return None 
Example #48
0
def create_or_update_external_user(
        external_username,
        auth_source,
        attributes={},
        first_name=u'',
        last_name=u'',
        email=u'',
        is_active=None,
        is_staff=None,
        is_superuser=None,
        groups=['users']):
    """
    Создание или обновление пользователя из внешней системы аутентификации
    :param external_username: Имя пользователя во внешней системе
    :param auth_source: Идентификатор внешней системы
    :param attributes: Хеш атрибутов внешнего пользователя
    :param first_name:
    :param last_name:
    :param email:
    :param is_active:
    :param is_staff:
    :param is_superuser:
    :param groups: названия групп, в которые нужно добавить пользователя
    :return:
    """
    cleaned_external_username = external_username.strip().lower()
    cleaned_auth_source = auth_source.strip().lower()
    print cleaned_external_username
    print cleaned_auth_source
    try:
        external_user = ExternalUser.objects.get(
            external_username=cleaned_external_username,
            auth_source=cleaned_auth_source
        )
        if external_user.get_attributes() != attributes:
            external_user.set_attributes(attributes)
            external_user.save()

        user_is_updated = False
        user = external_user.user

        if first_name and user.first_name != first_name:
            user.first_name = first_name
            user_is_updated = True

        if last_name and user.last_name != last_name:
            user.last_name = last_name
            user_is_updated = True

        if email and user.email != email:
            user.email = True
            user_is_updated = True

        if is_staff is not None and user.is_staff != is_staff:
            user.is_staff = is_staff
            user_is_updated = True

        if is_superuser is not None and user.is_superuser != is_superuser:
            user.is_superuser = is_superuser
            user_is_updated = True

        if is_active is not None and user.is_active != is_active:
            user.is_active = is_active
            user_is_updated = True

        if user_is_updated:
            user.save()

        if groups:
            exist_groups = Group.objects.filter(name__in=groups)
            user.groups.add(*exist_groups)

        return external_user
    except ExternalUser.DoesNotExist:
        external_user = ExternalUser(
            external_username=cleaned_external_username,
            auth_source=cleaned_auth_source
        )
        external_user.set_attributes(attributes)
        external_user.save()

        user = User(
            username=u'%s@sso' % (external_user.id,),
            first_name=first_name,
            last_name=last_name,
            email=email,
            is_staff=bool(is_staff),
            is_superuser=bool(is_superuser),
            is_active=bool(is_active)
        )
        user.set_unusable_password()
        user.save()

        if groups:
            exist_groups = Group.objects.filter(name__in=groups)
            user.groups.add(*exist_groups)

        external_user.user = user
        external_user.save()

        return external_user
Example #49
0
def splitusers(email_or_phone):
    email = None
    phone = None
    profile = None
    try:
        email = Email.objects.get(email=email_or_phone)
        profile = email.user
    except Email.DoesNotExist:
        phone = Phone.objects.get(phone=email_or_phone)
        profile = phone.user

    emails = profile.email_set.all()
    phones = profile.phone_set.all()

    for email in emails:
        if not email_re.match(email.email):
            print 'Invalid email %s' % email.email
            # XXX Delete this email
            continue

        with transaction.commit_on_success():
            try:
                au = User.objects.get(username=email.email)
                print 'Skipping splitting email %s' % email.email
            except User.DoesNotExist:
                au = User.objects.create_user(username=email.email,
                                              email.email)
                au.save()

                p = Profile(user=au)
                p.save()

                profile_remap = ProfileRemap(old_profile=email.user,
                                             new_profile=p,
                                             email=email)

                email.user = p
                email.save()

                profile_remap.save()

                print 'Created new profile for %s' % email.email

    for phone in phones:
        if not phone_re.match(phone.phone):
            print 'Invalid phone %s' % phone.phone
            # XXX Delete this phone
            continue

        with transaction.commit_on_success():
            try:
                au = User.objects.get(username=phone.phone)
                print 'Skipping splitting phone  %s' % phone.phone
            except User.DoesNotExist:
                au = User(username=email.email, email='')
                au.set_unusable_password()
                au.save()

                p = Profile(user=au)
                p.save()

                profile_remap = ProfileRemap(old_profile=phone.user,
                                             new_profile=p,
                                             phone=phone)

                phone.user = p
                phone.save()

                profile_remap.save()

                print 'Created new profile for %s' % email.email
Example #50
0
class ShibbolethTest(TestCase):
    def setUp(self):
        self.user = User(
            username='******',
            email='',
            first_name='Matti',
            last_name='Sukunimi',
        )
        self.user.set_unusable_password()
        self.user.save()
        self.user.userprofile.student_id = '000'
        self.user.userprofile.save()

        self.login_url = reverse('shibboleth_login.views.login')

    def test_invalid(self):
        meta = DEF_SHIBD_META.copy()
        del meta['SHIB_eppn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def test_valid_new(self):
        meta = DEF_SHIBD_META.copy()
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_without_email(self):
        meta = DEF_SHIBD_META.copy()
        del meta['SHIB_mail']
        del meta['SHIB_givenName']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '{:d}@localhost'.format(user.id))
        self.assertEqual(user.first_name, '')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_without_student_id(self):
        meta = DEF_SHIBD_META.copy()
        del meta['SHIB_schacPersonalUniqueCode']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 2)
        user = User.objects.get(username='******')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Teekkari')
        self.assertEqual(user.userprofile.student_id, None)

    def test_valid_old(self):
        meta = DEF_SHIBD_META.copy()
        meta['SHIB_eppn'] = self.user.username
        del meta['SHIB_sn']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Teemu')
        self.assertEqual(user.last_name, 'Sukunimi')
        self.assertEqual(user.userprofile.student_id, '123453')

    def test_nonascii(self):
        meta = DEF_SHIBD_META.copy()
        meta['SHIB_eppn'] = self.user.username.encode('utf-8')
        del meta['SHIB_givenName']
        meta['SHIB_sn'] = 'Meikäläinen'
        del meta['SHIB_schacPersonalUniqueCode']
        response = self._get(meta)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)
        user = User.objects.first()
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.first_name, 'Matti')
        self.assertEqual(user.last_name, 'Meikäläinen')
        self.assertEqual(user.userprofile.student_id, '000')

    def test_inactive(self):
        self.user.is_active = False
        self.user.save()
        meta = DEF_SHIBD_META.copy()
        meta['SHIB_eppn'] = self.user.username.encode('utf-8')
        response = self._get(meta)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(User.objects.count(), 1)

    def _get(self, meta):
        if settings.SHIBBOLETH_VARIABLES_URL_ENCODED:
            for key in meta.keys():
                meta[key] = urllib.parse.quote(meta[key])
        return self.client.generic('GET', self.login_url, **meta)
Example #51
0
    def test_o2o_cross_database_protection(self):
        "Operations that involve sharing FK objects across databases raise an error"
        # Create a user and profile on the default database
        alice = User.objects.db_manager('default').create_user('alice', '*****@*****.**')

        # Create a user and profile on the other database
        bob = User.objects.db_manager('other').create_user('bob', '*****@*****.**')

        # Set a one-to-one relation with an object from a different database
        alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
        try:
            bob.userprofile = alice_profile
            self.fail("Shouldn't be able to assign across databases")
        except ValueError:
            pass

        # BUT! if you assign a FK object when the base object hasn't
        # been saved yet, you implicitly assign the database for the
        # base object.
        bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')

        new_bob_profile = UserProfile(flavor="spring surprise")
        new_bob_profile.save(using='other')

        charlie = User(username='******',email='*****@*****.**')
        charlie.set_unusable_password()
        charlie.save(using='other')

        # old object comes from 'other', so the new object is set to use 'other'...
        new_bob_profile.user = bob
        charlie.userprofile = bob_profile
        self.assertEqual(new_bob_profile._state.db, 'other')
        self.assertEqual(charlie._state.db, 'other')

        # When saved (no using required), new objects goes to 'other'
        bob_profile.save()
        self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)),
                          [u'alice'])
        self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
                          [u'bob', u'charlie'])
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise'])

        # This also works if you assign the O2O relation in the constructor
        denise = User.objects.db_manager('other').create_user('denise','*****@*****.**')
        denise_profile = UserProfile(flavor="tofu", user=denise)

        self.assertEqual(denise_profile._state.db, 'other')
        # ... but it isn't saved yet
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise'])

        # When saved, the new profile goes to 'other'
        denise_profile.save()
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise', u'tofu'])
Example #52
0
def _get_or_create_oauth_user(strategy,
                              detail,
                              request=None,
                              mobile_client=False,
                              created_on='web'):
    '''
    strategy -- strategy obj
    detail -- oauth登录拿到token时的response
    '''
    backend = strategy.backend
    _created = False
    uid = get_uid(strategy, detail)
    # weibo新接口uid改名叫做id
    if not uid:
        uid = detail.get('id')
    # weixin
    if backend.name in ('weixin', 'weixinapp'):
        weixin_unionid = detail.get('unionid')
        if weixin_unionid:
            weixin_users = UserSocialAuth.objects.filter(
                weixin_unionid=weixin_unionid).order_by('id')
            weixin_users_count = weixin_users.count()
            # 微信只有一个UserSocialAuth时,使用这个
            if weixin_users_count == 1:
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__,
                                          backend.__class__.__name__)
                return (user, False)
            elif weixin_users_count > 1:
                # 有web则永远返回第一个web用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith('web'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 否则返回mobile用户
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith(
                            'mobile'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 否则返回weixin app用户(微信服务号活动生成)
                for each in weixin_users:
                    if each.created_on and each.created_on.startswith('app'):
                        user = each.user
                        user.backend = "%s.%s" % (backend.__module__,
                                                  backend.__class__.__name__)
                        return (user, False)
                # 没有第四种逻辑, 但是还是加上吧
                user = weixin_users[0].user
                user.backend = "%s.%s" % (backend.__module__,
                                          backend.__class__.__name__)
                return (user, False)
    if backend.name == 'chinamobile':
        extra_data = backend.extra_data(None, uid, detail, {})
        phone_number = extra_data.get('phone_number', None)
        try:
            user_profile = UserProfile.objects.get(phone_number=phone_number)
            user = user_profile.user
            user.backend = "%s.%s" % (backend.__module__,
                                      backend.__class__.__name__)
            return (user, False)
        except:
            pass
    result = social_user(strategy, uid)
    # 已有账户,直接登录
    if result['user']:
        user = result['user']
    # 否则创建用户,之后登录
    else:
        user = User()
        user.username = str(uuid.uuid4()).replace('-', '')[:20]
        user.email = None
        # oauth的自动激活
        user.is_active = True
        user.set_unusable_password()
        user.save()
        extra_data = backend.extra_data(user, uid, detail, {})
        profile = UserProfile(user=user)
        nickname = get_validate_nickname(extra_data['username'])
        oauth_nickname = nickname
        # 重名加后缀,最多尝试10次
        MAX_TRY_TIMES = 10
        while MAX_TRY_TIMES:
            try:
                UserProfile.objects.get(nickname=nickname)
                suffix = str(uuid.uuid4().int)[:6]
                nickname = '{}{}'.format(oauth_nickname, suffix)
                MAX_TRY_TIMES = MAX_TRY_TIMES - 1
            except UserProfile.DoesNotExist:
                break
        profile.phone_number = extra_data.get('phone_number', None)
        profile.nickname = nickname
        profile.unique_code = profile.get_unique_code()
        if request:
            profile.set_register_extra(request=request,
                                       cover_data={'channel': backend.name})
        if extra_data.get('profile_image_url'):
            profile.avatar = extra_data['profile_image_url']
        if extra_data.get('gender'):
            profile.gender = extra_data['gender']
        if extra_data.get('year_of_birth'):
            profile.year_of_birth = extra_data['year_of_birth']
        if backend.name == 'chinamobile':
            profile.register_type = 'migu'
            profile.register_auto = 1
        profile.save()
        # TODO: AuthAlreadyAssociated
        # 此oauth账号之前已经绑定了学堂在线的账号
        new_associate_user(strategy, uid, user, detail, created_on=created_on)
        _created = True
        # Track this user register event in oauth
        if not mobile_client:  # do not track api client log 2015.5.26
            event_type = 'weixinapp.user.register_success' if created_on == 'weixinapp' else 'oauth.user.register_success'
            track_log(request, event_type, {
                'success': True,
                'uid': user.id,
                'provider': backend.name,
            })
    user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
    return (user, _created)