コード例 #1
0
ファイル: views.py プロジェクト: Stevenholloway/SHARE
    def populate_user(self, request, sociallogin, data):
        """
        Hook that can be used to further populate the user instance.

        For convenience, we populate several common fields.

        Note that the user instance being populated represents a
        suggested User instance that represents the social user that is
        in the process of being logged in.

        The User instance need not be completely valid and conflict
        free. For example, verifying whether or not the username
        already exists, is not a responsibility.
        """
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        name = data.get('name')
        time_zone = data.get('time_zone')
        locale = data.get('locale')
        gravatar = data.get('profile_image_url')
        user = sociallogin.user
        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')
        name_parts = (name or '').partition(' ')
        user_field(user, 'first_name', first_name or name_parts[0])
        user_field(user, 'last_name', last_name or name_parts[2])
        user_field(user, 'time_zone', time_zone)
        user_field(user, 'locale', locale)
        user_field(user, 'gravatar', gravatar)
        return user
コード例 #2
0
def update_profile(sociallogin):
    """Update a people.models.Profile object with info from the sociallogin"""
    user = sociallogin.user
    extractor = get_data_extractor(sociallogin.account.provider)
    if extractor is not None:
        profile_fields = (
            "username",
            "email",
            "area",
            "city",
            "country",
            "delivery",
            "fax",
            "first_name",
            "last_name",
            "organization",
            "position",
            "profile",
            "voice",
            "zipcode"
        )
        for field in profile_fields:
            try:
                extractor_method = getattr(
                    extractor, "extract_{}".format(field))
                value = extractor_method(sociallogin.account.extra_data)
                user_field(user, field, value)
            except (AttributeError, NotImplementedError):
                pass  # extractor doesn't define a method for extracting field
    return user
コード例 #3
0
 def save_user(self, request, user, form, commit=True):
     data = form.cleaned_data
     first_name = data.get('first_name')
     last_name = data.get('last_name')
     email = data.get('email')
     username = data.get('username').lower()
     user_email(user, email)
     user_username(user, username)
     if first_name:
        user_field(user, 'first_name', first_name)
     if last_name:
        user_field(user, 'last_name', last_name)
     if 'password1' in data:
        user.set_password(data["password1"])
     else:
        user.set_unusable_password()
     self.populate_username(request, user)
     user.id_group_id = data.get("id_group")
     user.document = data.get("document")
     user.type_document = data.get('type_document')
     user.phone_home = data.get('phone_home')
     user.phone_mobile = data.get('phone_mobile')
     user.city = data.get('city')
     user.phone_office = data.get('phone_office')
     if commit:
             user.save()
     return user
コード例 #4
0
ファイル: views.py プロジェクト: iobis/geonode
def user_info(request):
    headers = extract_headers(request)
    user = request.user

    if not user:
        out = {
            'success': False,
            'status': 'error',
            'errors': {
                'user': ['User is not authenticated']
            }
        }
        return json_response(out, status=401)

    access_token = None
    if 'Authorization' not in headers or 'Bearer' not in headers[
            "Authorization"]:
        access_token = get_auth_token(user)
        if not access_token:
            out = {
                'success': False,
                'status': 'error',
                'errors': {
                    'auth': ['No token provided.']
                }
            }
            return json_response(out, status=403)
    else:
        access_token = headers["Authorization"].replace('Bearer ', '')

    groups = [group.name for group in user.groups.all()]
    if user.is_superuser:
        groups.append("admin")

    user_info = json.dumps({
        "sub":
        str(user.id),
        "name":
        " ".join(
            [user_field(user, 'first_name'),
             user_field(user, 'last_name')]),
        "given_name":
        user_field(user, 'first_name'),
        "family_name":
        user_field(user, 'last_name'),
        "email":
        user_email(user),
        "preferred_username":
        user_username(user),
        "groups":
        groups,
        "access_token":
        str(access_token)
    })

    response = HttpResponse(user_info, content_type="application/json")
    response['Cache-Control'] = 'no-store'
    response['Pragma'] = 'no-cache'

    return response
コード例 #5
0
 def populate_user(self, request, sociallogin, data):
     user = sociallogin.user
     username = data.get('username')
     first_name = data.get('first_name')
     last_name = data.get('last_name')
     if sociallogin.account.provider == 'twitter':
         email = '{}@twitter.com'.format(username)
     else:
         email = data.get('email')
         birthday = sociallogin.account.extra_data.get('birthday')
         if birthday:
             user_field(
                 user, 'data_de_nascimento', '{}'.format(
                     datetime.strptime(birthday,
                                       '%m/%d/%Y').strftime('%Y-%m-%d')))
     name = data.get('name')
     user_username(user, username or '')
     user_email(user, valid_email_or_none(email) or '')
     name_parts = (name or '').partition(' ')
     first_name = first_name or name_parts[0]
     last_name = last_name or name_parts[2]
     user_field(user, 'nome',
                u'{} {}'.decode('utf-8').format(first_name, last_name))
     if not user.data_ativacao_email:
         user.data_ativacao_email = timezone.now()
     return user
コード例 #6
0
    def save_user(self, request, user, form, commit=True):
        """
        save_userをオーバライド
        ユーザ保存時の処理を定義
        """
        data = form.cleaned_data
        username = data.get('username')
        email = data.get('email')
        """
        django-allauth/allauth/account/utils.pyのuser_fieldを使用
        setattr(user, field, fieldの値)でuserのプロパティに値を入れている。
        """
        user_field(user, 'username', username)
        user_email(user, email)
        """
        プロフィール画像が選択されていれば登録する
        選択されていない場合は「no-image」を登録する
        """

        if request.FILES.get('profile_pic'):
            profile_pic_file = request.FILES.get('profile_pic')
            profile_pic_name = username + '_' + profile_pic_file.name

            user.profile_pic.save(profile_pic_name, profile_pic_file)

        if 'password1' in data:
            user.set_password(data.get('password1'))
        else:
            user.set_unusable_password()
        self.populate_username(request, user)

        if commit:
            user.save()
        return user
コード例 #7
0
ファイル: adapters.py プロジェクト: GeoNode/geonode
def update_profile(sociallogin):
    """Update a people.models.Profile object with info from the sociallogin"""
    user = sociallogin.user
    extractor = get_data_extractor(sociallogin.account.provider)
    if extractor is not None:
        profile_fields = (
            "area",
            "city",
            "country",
            "delivery",
            "fax",
            "first_name",
            "last_name",
            "organization",
            "position",
            "profile",
            "voice",
            "zipcode",
        )
        for field in profile_fields:
            try:
                extractor_method = getattr(
                    extractor, "extract_{}".format(field))
                value = extractor_method(sociallogin.account.extra_data)
                user_field(user, field, value)
            except (AttributeError, NotImplementedError):
                pass  # extractor doesn't define a method for extracting field
    return user
コード例 #8
0
ファイル: adapter.py プロジェクト: larry852/redzza
 def populate_user(self,
                   request,
                   sociallogin,
                   data):
     """
     Hook that can be used to further populate the user instance.
     For convenience, we populate several common fields.
     Note that the user instance being populated represents a
     suggested User instance that represents the social user that is
     in the process of being logged in.
     The User instance need not be completely valid and conflict
     free. For example, verifying whether or not the username
     already exists, is not a responsibility.
     """
     first_name = data.get('first_name')
     last_name = data.get('last_name')
     email = data.get('email')
     name = data.get('name')
     user = sociallogin.user
     name_parts = (name or '').partition(' ')
     user_field(user, 'first_name', first_name or name_parts[0])
     user_field(user, 'last_name', last_name or name_parts[2])
     username = utils.generateRandomUsername(first_name or name_parts[0] or '')
     user_email(user, valid_email_or_none(email) or (username + '@redzza.com'))
     user_username(user, username)
     return user
コード例 #9
0
    def populate_user(self, request, sociallogin, data):
        """
        Hook that can be used to further populate the user instance.

        For convenience, we populate several common fields.

        Note that the user instance being populated represents a
        suggested User instance that represents the social user that is
        in the process of being logged in.

        The User instance need not be completely valid and conflict
        free. For example, verifying whether or not the username
        already exists, is not a responsibility.
        """
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        name = data.get('name')
        time_zone = data.get('time_zone')
        locale = data.get('locale')
        gravatar = data.get('profile_image_url')
        user = sociallogin.user
        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')
        name_parts = (name or '').partition(' ')
        user_field(user, 'first_name', first_name or name_parts[0])
        user_field(user, 'last_name', last_name or name_parts[2])
        user_field(user, 'time_zone', time_zone)
        user_field(user, 'locale', locale)
        user_field(user, 'gravatar', gravatar)
        return user
コード例 #10
0
ファイル: adapter.py プロジェクト: Hirochon/Shappar
    def save_user(self, request, user, form, commit=True):
        """allauthのsave_userを再定義→ユーザ保存時の処理を追加"""

        data = form.cleaned_data
        username = data.get('username')
        email = data.get('email')
        user.usernonamae = data.get('usernonamae')
        user.sex = data.get('sex')
        user.age = data.get('age')
        user.blood_type = data.get('blood_type')
        user.born_at = data.get('born_at')
        user.introduction = data.get('introduction')

        # django-allauth/allauth/account/utils.pyのuser_fieldを使用
        user_field(user, 'username', username)
        user_email(user, email)

        if 'password1' in data:
            user.set_password(data.get('password1'))
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            user.save()
        return user
コード例 #11
0
ファイル: adapters.py プロジェクト: MarkAPhillips/auth-api
 def save_user(self, request, user, form, commit=True):
     from allauth.account.utils import user_field
     user = super().save_user(request, user, form, False)
     user_field(user, 'first_name', request.data.get('first_name', ''))
     user_field(user, 'last_name', request.data.get('last_name', ''))
     user.save()
     return user
コード例 #12
0
    def save_user(self, request, user, form, commit=True):
        data = form.cleaned_data
        unregistered_user = data.get('unregistered_user')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = email
        password = data['password']
        is_staff = unregistered_user.is_staff

        user_field(user, 'first_name', first_name)
        user_field(user, 'last_name', last_name)
        user_email(user, email)
        user_username(user, username)
        user.set_password(password)
        user.is_staff = is_staff

        self.populate_username(request, user)
        if commit:
            user.save()

        Profile.objects.create(user=user)

        if is_staff:
            Teacher.objects.create(user=user)
        else:
            Student.objects.create(user=user, group=unregistered_user.group)

        unregistered_user.delete()

        return user
コード例 #13
0
    def populate_user(self, request, sociallogin, data):
        """
        Hook that can be used to further populate the user instance.

        For convenience, we populate several common fields.

        Note that the user instance being populated represents a
        suggested User instance that represents the social user that is
        in the process of being logged in.

        The User instance need not be completely valid and conflict
        free. For example, verifying whether or not the username
        already exists, is not a responsibility.
        """
        username = data.get('username')
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = username
        time_zone = data.get('time_zone')
        locale = data.get('locale')
        gravatar = data.get('profile_image_url')
        user = sociallogin.user
        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')
        user_field(user, 'given_name', first_name or '')
        user.is_active = True
        user.is_researcher = True
        user_field(user, 'family_name', last_name or '')
        user_field(user, 'time_zone', time_zone)
        user_field(user, 'locale', locale)
        user_field(user, '_identicon', self.get_base64_gravatar(gravatar))

        return user
コード例 #14
0
ファイル: adapter.py プロジェクト: allyjweir/lackawanna
    def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from allauth.account.utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        if first_name:
            user_field(user, 'first_name', first_name)
        if last_name:
            user_field(user, 'last_name', last_name)
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)

        user.is_active = False
        
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user
コード例 #15
0
	def save_user(self, request, user, form):
		data = form.cleaned_data
		email = data['email']
		first_name = data["first_name"]
		last_name = data["last_name"]
		username = generate_unique_username([first_name,last_name,email,'user'])
		user_email(user, email)
		user_username(user, username)
		user_field(user, 'first_name', first_name or '')
		user_field(user, 'last_name', last_name or '')
		password = data.get("password1")
		if password:
			user.set_password(password)
		else:
			user.set_unusable_password()
		user.save()
		avatar = Photo.objects.create(caption=first_name + " " + last_name + " Avatar", \
							user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_male_icon'],
							unique_id=generate_unique_id("photo"),photo_type='user_profile')

		
		cover_picture = Photo.objects.create(caption=first_name + " " + last_name + " Cover Picture", \
							user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_cover_picture'],
							unique_id=generate_unique_id("photo"),photo_type='user_profile')

		get_location_from_client_ip(request,user)
		user.get_profile().avatar = avatar
		user.get_profile().cover_picture = cover_picture
		user.get_profile().save()
		return user
コード例 #16
0
	def populate_user(self,request,sociallogin,data):
		socialaccount = sociallogin.account
		username = data.get('username')
		first_name = data.get('first_name')
		last_name = data.get('last_name')
		email = data.get('email')
		name = data.get('name')
		user = sociallogin.account.user
		user_model = get_user_model()

		try:
			query = {"username" + '__iexact': username}
			user_model.objects.get(**query)
			user_username(user,generate_unique_username([first_name,last_name,email,'user']))
		except Exception as e:
			if username == None:
				user_username(user,generate_unique_username([first_name,last_name,email,'user']))
			else:
				user_username(user,username.replace(".",""))

		user_email(user, valid_email_or_none(email) or '')
		name_parts = (name or '').partition(' ')
		user_field(user, 'first_name', first_name or name_parts[0])
		user_field(user, 'last_name', last_name or name_parts[2])
		return user
コード例 #17
0
ファイル: authentication.py プロジェクト: fossabot/foxtail
    def populate_user(self, request, sociallogin, data):
        username = data.get('username')
        email = data.get('email')

        user = sociallogin.user

        user_username(user, username or '')
        user_email(user, valid_email_or_none(email) or '')

        date_of_birth = data.get('birthdate')
        if date_of_birth:
            try:
                parsed = datetime.strptime(date_of_birth, "%Y-%m-%d")
                user.date_of_birth = parsed
            except ValueError:
                pass

        name = data.get('name')
        first_name = data.get('first_name')
        last_name = data.get('last_name')

        # if a full name exists, use that, if not,
        # join first_name and last_name
        if name:
            user_field(user, 'full_name', name)
        else:
            merged = ' '.join(x for x in [first_name, last_name] if x)
            if merged != '':
                user_field(user, 'full_name', merged)

        return user
コード例 #18
0
def _process_signup(request, sociallogin):
    # If email is specified, check for duplicate and if so, no auto signup.
    auto_signup = app_settings.AUTO_SIGNUP
    email = user_email(sociallogin.account.user)
    if auto_signup:
        # Let's check if auto_signup is really possible...
        if email:
            if account_settings.UNIQUE_EMAIL:
                if email_address_exists(email):
                    # Oops, another user already has this address.  We
                    # cannot simply connect this social account to the
                    # existing user. Reason is that the email adress may
                    # not be verified, meaning, the user may be a hacker
                    # that has added your email address to his account in
                    # the hope that you fall in his trap.  We cannot check
                    # on 'email_address.verified' either, because
                    # 'email_address' is not guaranteed to be verified.
                    auto_signup = False
                    # FIXME: We redirect to signup form -- user will
                    # see email address conflict only after posting
                    # whereas we detected it here already.
        elif app_settings.EMAIL_REQUIRED:
            # Nope, email is required and we don't have it yet...
            auto_signup = False
    if not auto_signup:
        request.session['socialaccount_sociallogin'] = sociallogin
        url = reverse('socialaccount_signup')
        ret = HttpResponseRedirect(url)
    else:
        # FIXME: This part contains a lot of duplication of logic
        # ("closed" rendering, create user, send email, in active
        # etc..)
        try:
            if not get_account_adapter().is_open_for_signup(request):
                return render(request, "account/signup_closed.html")
        except ImmediateHttpResponse as e:
            return e.response
        u = sociallogin.account.user
        if account_settings.USER_MODEL_USERNAME_FIELD:
            user_username(
                u,
                generate_unique_username(user_username(u) or email or 'user'))
        for field in ['last_name', 'first_name']:
            if hasattr(u, field):
                truncated_value = (user_field(u, field) or '') \
                    [0:User._meta.get_field(field).max_length]
                user_field(u, field, truncated_value)
        user_email(u, email or '')
        u.set_unusable_password()
        sociallogin.save(request)
        from allauth.account.models import EmailAddress
        email_address = EmailAddress.objects.get(user=u, email__iexact=email)
        if app_settings.AUTO_EMAIL_VERIFY == True:
            email_address.verified = True
            email_address.save()

        #send_email_confirmation(request, u)
        ret = complete_social_signup(request, sociallogin)
    return ret
コード例 #19
0
ファイル: adapters.py プロジェクト: AIDARXAN/akyn
    def save_user(self, request, user, form, commit=True):
        user = super().save_user(request, user, form, False)
        user_field(user, 'first_name', request.data.get('first_name', ''))
        user_field(user, 'last_name', request.data.get('last_name', ''))
        if commit:
            user.save()

        return user
コード例 #20
0
 def save_user(self, request, user, form, commit=True):
     display_name = form.cleaned_data.get("display_name")
     logger.debug("Found requested display_name of {0} for {1}".format(
         display_name, form.cleaned_data["username"]))
     if display_name:
         logger.debug("Attempting to save to model field.")
         user_field(user, "display_name", display_name)
     return super().save_user(request, user, form, commit)
コード例 #21
0
ファイル: helpers.py プロジェクト: pilva/django-allauth
def _process_signup(request, sociallogin):
    # If email is specified, check for duplicate and if so, no auto signup.
    auto_signup = app_settings.AUTO_SIGNUP
    email = user_email(sociallogin.account.user)
    if auto_signup:
        # Let's check if auto_signup is really possible...
        if email:
            if account_settings.UNIQUE_EMAIL:
                if email_address_exists(email):
                    # Oops, another user already has this address.  We
                    # cannot simply connect this social account to the
                    # existing user. Reason is that the email adress may
                    # not be verified, meaning, the user may be a hacker
                    # that has added your email address to his account in
                    # the hope that you fall in his trap.  We cannot check
                    # on 'email_address.verified' either, because
                    # 'email_address' is not guaranteed to be verified.
                    auto_signup = False
                    # FIXME: We redirect to signup form -- user will
                    # see email address conflict only after posting
                    # whereas we detected it here already.
        elif app_settings.EMAIL_REQUIRED:
            # Nope, email is required and we don't have it yet...
            auto_signup = False
    if not auto_signup:
        request.session['socialaccount_sociallogin'] = sociallogin
        url = reverse('socialaccount_signup')
        ret = HttpResponseRedirect(url)
    else:
        # FIXME: This part contains a lot of duplication of logic
        # ("closed" rendering, create user, send email, in active
        # etc..)
        try:
            if not get_account_adapter().is_open_for_signup(request):
                return render(request,
                              "account/signup_closed.html")
        except ImmediateHttpResponse as e:
            return e.response
        u = sociallogin.account.user
        if account_settings.USER_MODEL_USERNAME_FIELD:
            user_username(u,
                          generate_unique_username(user_username(u)
                                                   or email
                                                   or 'user'))
        for field in ['last_name',
                      'first_name']:
            if hasattr(u, field):
                truncated_value = (user_field(u, field) or '') \
                    [0:User._meta.get_field(field).max_length]
                user_field(u, field, truncated_value)
        user_email(u, email or '')
        if u.password:
            pass
        else:
            u.set_unusable_password()
        sociallogin.save(request)
        ret = complete_social_signup(request, sociallogin)
    return ret
コード例 #22
0
 def populate_user(self, request, sociallogin, data):
     name = data.get('name')
     email = data.get('email')
     provider = data.get('provider')
     user = sociallogin.user
     user_email(user, valid_email_or_none(email) or '')
     user_field(user, 'name', name)
     user_field(user, 'provider', provider)
     return user
コード例 #23
0
ファイル: adapters.py プロジェクト: IllyaArtemchuk/QuizSystem
 def save_user(self, request, user, form, commit=True):
     """
     Saves a new `User` instance using information provided in the signup form.
     """
     from allauth.account.utils import user_field
     user = super().save_user(request, user, form, False)
     user_field(user, 'role', request.data.get('role', ''))
     user.save()
     return user
コード例 #24
0
 def save_user(self, request, sociallogin, form=None):
     user = super(UnescoLocalAccountAdapter, self).save_user(request,
                                                             sociallogin,
                                                             form=form)
     if form:
         recommendation = form.cleaned_data["recommendation"]
         user_field(user, 'recommendation', recommendation or None)
         user.save()
     return user
コード例 #25
0
ファイル: adapter.py プロジェクト: yverdon/geocity
 def get_signup_form_initial_data(self, sociallogin):
     user = sociallogin.user
     initial = {
         "email": utils.user_email(user) or "",
         "username": utils.user_username(user) or "",
         "first_name": utils.user_field(user, "first_name") or "",
         "last_name": utils.user_field(user, "last_name") or "",
     }
     return initial
コード例 #26
0
ファイル: adapter.py プロジェクト: SlashKing/ctdev-DJANGO
 def get_signup_form_initial_data(self, sociallogin):
     user = sociallogin.user
     initial = {
         'email': user_email(user) or '',
         'username': user_username(user) or '',
         'first_name': user_field(user, 'first_name') or '',
         'last_name': user_field(user, 'last_name') or ''
     }
     return initial
コード例 #27
0
    def save_user(self, request, user, form, commit=True):
        from allauth.account.utils import user_field

        user = super().save_user(request, user, form, False)
        user_field(user, 'is_manager', request.data.get('is_manager', ''))
        user_field(user, 'client_company_id',
                   request.data.get('client_company_id', ''))
        user.save()
        return user
コード例 #28
0
ファイル: forms.py プロジェクト: flebel/django-allauth
 def __init__(self, *args, **kwargs):
     self.sociallogin = kwargs.pop('sociallogin')
     user = self.sociallogin.account.user
     initial = {'email': user_email(user) or '',
                'username': user_username(user) or '',
                'first_name': user_field(user, 'first_name') or '',
                'last_name': user_field(user, 'last_name') or ''}
     kwargs['initial'] = initial
     kwargs['email_required'] = app_settings.EMAIL_REQUIRED
     super(SignupForm, self).__init__(*args, **kwargs)
コード例 #29
0
ファイル: forms.py プロジェクト: bopopescu/kariro-azure
 def __init__(self, *args, **kwargs):
     self.sociallogin = kwargs.pop('sociallogin')
     user = self.sociallogin.account.user
     initial = {'email': user_email(user) or '',
                'username': user_username(user) or '',
                'first_name': user_field(user, 'first_name') or '',
                'last_name': user_field(user, 'last_name') or ''}
     kwargs['initial'] = initial
     kwargs['email_required'] = app_settings.EMAIL_REQUIRED
     super(SignupForm, self).__init__(*args, **kwargs)
コード例 #30
0
 def save_user(self, request, user, form, commit=True):
     """  save a new user """
     from allauth.account.utils import user_field
     user = super().save_user(request,user,form,False)
     user_field(user,'username',request.data.get('username',''))
     user_field(user,'password1',request.data.get('password1',''))
     user_field(user,'password2',request.data.get('password2',''))
     user_field(user,'email',request.data.get('email',''))
     user_field(user,'user_type',request.data.get('user_type',''))
     user.save()
     return user
コード例 #31
0
ファイル: adapter.py プロジェクト: tobby2002/VeraWebApp
    def save_user(self, request, user, form, commit=True):
        from allauth.account.utils import user_field

        data = form.cleaned_data
        phone_number = data.get('phone_number')
        country_code = data.get('country_code')
        if phone_number:
            user_field(user, 'phone_number', phone_number)
        if country_code:
            user_field(user, 'country_code', country_code)
        return super().save_user(request, user, form, commit)
コード例 #32
0
ファイル: serializers.py プロジェクト: rubythonode/sosaServer
 def custom_signup(self, request, user, commit=True):
     data = self.cleaned_data
     birth = data.get('birth')
     gender = data.get('gender')
     if birth:
         setattr(user, 'birth', birth)
     if gender:
         user_field(user, 'gender', gender)
     if commit:
         user.save()
     return user
コード例 #33
0
ファイル: views.py プロジェクト: toobigtoignore/issf
 def save_user(self, user, first_name, last_name, email, username):
     user_email(user, email)
     user_username(user, username)
     user_field(user, 'first_name', first_name or '')
     user_field(user, 'last_name', last_name or '')
     password = username
     while len(password) < 6:
         password = password + '1'
     user.set_password(username)
     user.save()
     return user
コード例 #34
0
    def populate_username(self, request, user):
        # validate the already generated username with django validation
        # if it passes use that, otherwise use django-allauth's way of
        # generating a unique username

        # safe_username = user_username(user)
        try:
            safe_username = populate_username(user_field(user, 'first_name'),
                                              user_field(user, 'last_name'))
        except Exception, e:
            traceback.print_exc()
            raise forms.ValidationError(e)
コード例 #35
0
 def populate_username(self, request, user):
     """
     Fills in a valid username, if required and missing.  If the
     username is already present it is assumed to be valid
     (unique).
     """
     first_name = user_field(user, "first_name")
     last_name = user_field(user, "last_name")
     email = user_email(user)
     username = user_username(user)
     if USER_MODEL_USERNAME_FIELD:
         user_username(user, username or generate_unique_username([first_name, last_name, email, "user"]))
コード例 #36
0
 def save_user(self, request, user, form, commit=True):
     """
     Saves a new `User` instance using information provided in the
     signup form.
     """
     from allauth.account.utils import user_field
     username = request.data.get('username', '')
     address = W3.personal.newAccount(username)
     user = super().save_user(request, user, form, False)
     user_field(user, 'address', address)
     user.save()
     return user
コード例 #37
0
 def __init__(self, *args, **kwargs):
     self.sociallogin = kwargs.pop('sociallogin')
     user = self.sociallogin.account.user
     # TODO: Should become more generic, not listing
     # a few fixed properties.
     initial = {'email': user_email(user) or '',
                'username': user_username(user) or '',
                'first_name': user_field(user, 'first_name') or '',
                'last_name': user_field(user, 'last_name') or ''}
     kwargs['initial'] = initial
     kwargs['email_required'] = app_settings.EMAIL_REQUIRED
     super(SignupForm, self).__init__(*args, **kwargs)
コード例 #38
0
ファイル: forms.py プロジェクト: VuongN/django-allauth
 def __init__(self, *args, **kwargs):
     self.sociallogin = kwargs.pop("sociallogin")
     user = self.sociallogin.account.user
     initial = {
         "email": user_email(user) or "",
         "username": user_username(user) or "",
         "first_name": user_field(user, "first_name") or "",
         "last_name": user_field(user, "last_name") or "",
     }
     kwargs["initial"] = initial
     kwargs["email_required"] = app_settings.EMAIL_REQUIRED
     super(SignupForm, self).__init__(*args, **kwargs)
コード例 #39
0
ファイル: adapters.py プロジェクト: kili/dashboard
    def save_user(self, request, user, form, commit=True):
        data = form.cleaned_data
        company = data.get("company")
        utils.user_field(user, "company", company)
        AsyncTasks.save_user.apply_async(
            kwargs={
                "company": data["company"],
                "user_name": data["email"],
                "password": data["password1"],
                "email": data["email"],
            },
            link=AsyncTasks.update_keystone_id.s(data["email"]),
        )

        return super(CompanyAdapter, self).save_user(request, user, form, commit)
コード例 #40
0
ファイル: adapters.py プロジェクト: GeoNode/geonode
 def populate_username(self, request, user):
     # validate the already generated username with django validation
     # if it passes use that, otherwise use django-allauth's way of
     # generating a unique username
     try:
         user.full_clean()
         safe_username = user_username(user)
     except ValidationError:
         safe_username = self.generate_unique_username([
             user_field(user, 'first_name'),
             user_field(user, 'last_name'),
             user_email(user),
             user_username(user)
         ])
     user_username(user, safe_username)
コード例 #41
0
def revert_usernames(apps, schema_editor):
    User = apps.get_model('auth', 'User')

    for user in User.objects.exclude(username='******'):
        old_username = user.username
        user_username(
            user,
            generate_unique_username([
                user_field(user, 'first_name'),
                user_field(user, 'last_name'),
                user_email(user),
                user_username(user),
            ])
        )
        if user_username(user) != old_username:
            user.save()
コード例 #42
0
def fix_usernames(apps, schema_editor):
    User = apps.get_model('auth', 'User')
    for user in User.objects.exclude(username='******'):
        if user.email and '@' in user.email:
            email_username = user.email.split('@')[0]
            old_username = user.username
            user_username(
                user,
                generate_unique_username([
                    email_username,
                    user_field(user, 'first_name'),
                    user_field(user, 'last_name'),
                    user_email(user),
                    user_username(user),
                ])
            )
            if user_username(user) != old_username:
                user.save()
コード例 #43
0
ファイル: views.py プロジェクト: GeoNode/geonode
def user_info(request):
    headers = extract_headers(request)
    user = request.user

    if not user:
        out = {'success': False,
               'status': 'error',
               'errors': {'user': ['User is not authenticated']}
               }
        return json_response(out, status=401)

    if 'Authorization' not in headers and 'Bearer' not in headers["Authorization"]:
        out = {'success': False,
               'status': 'error',
               'errors': {'auth': ['No token provided.']}
               }
        return json_response(out, status=403)

    groups = [group.name for group in user.groups.all()]
    if user.is_superuser:
        groups.append("admin")

    user_info = json.dumps({
        "sub": str(user.id),
        "name": " ".join([user_field(user, 'first_name'), user_field(user, 'last_name')]),
        "given_name": user_field(user, 'first_name'),
        "family_name": user_field(user, 'last_name'),
        "email": user_email(user),
        "preferred_username": user_username(user),
        "groups": groups
    })

    response = HttpResponse(
        user_info,
        content_type="application/json"
    )
    response['Cache-Control'] = 'no-store'
    response['Pragma'] = 'no-cache'
    return response
コード例 #44
0
 def save_user(self, request, user, form, commit=False):
     """
     Saves a new `User` instance using information provided in the
     signup form.
     """
     # user_field(user, 'date_of_birth', date_of_birth)
     # when field date_of_birth  (datetime.date(1975, 11, 11),)
     # is evaluated by  user_field, utils.py:80
     #     v = v[0:User._meta.get_field(field).max_length]
     # (or even just v[0] is evaluated on it's own)
     # {TypeError}'datetime.date' object has no attribute '__getitem__'
     # is thrown
     from allauth.account.utils import user_username, user_email, user_field
     data = form.cleaned_data
     first_name = data.get('first_name')
     last_name = data.get('last_name')
     email = data.get('email')
     username = data.get('username')
     date_of_birth = data.get('date_of_birth')
     gender = data.get('gender')
     user_email(user, email)
     user_username(user, username)
     user_field(user, 'first_name', first_name or '')
     user_field(user, 'last_name', last_name or '')
     user_field(user, 'gender', gender or '')
     user_field(user, 'date_of_birth', date_of_birth)
     if 'password1' in data:
         user.set_password(user,  data["password1"])
     else:
         user.set_unusable_password()
     self.populate_username(request, user)
     if commit:
         # Ability not to commit makes it easier to derive from
         # this adapter by adding
         user.save()
     print user
     return user
コード例 #45
0
 def populate_user(self, request, sociallogin, data):
     first_name = data.get("first_name")
     last_name = data.get("last_name")
     email = data.get("email")
     name = data.get("name")
     username = data.get("username")
     user = sociallogin.account.user
     # TODO: Consider using the super class for the stuff that is not unique to facebook!
     if sociallogin.account.provider == "facebook":
         user_email(user, valid_email_or_none(email) or "")
         name_parts = (name or "").partition(" ")
         user_field(user, "first_name", first_name or name_parts[0])
         user_field(user, "last_name", last_name or name_parts[2])
         # Save a good username
         if username:
             username_suggestions = [username, first_name, last_name, email, "user"]
         else:
             username_suggestions = [first_name, last_name, email, "user"]
         user_username(user, generate_unique_username(username_suggestions))
         return user
     elif sociallogin.account.provider == "twitter":
         if "screen_name" in sociallogin.account.extra_data.keys():
             username = sociallogin.account.extra_data["screen_name"]
         user_email(user, valid_email_or_none(email) or "")
         name_parts = (name or "").partition(" ")
         user_field(user, "first_name", first_name or name_parts[0])
         user_field(user, "last_name", last_name or name_parts[2])
         # Save a good username
         if username:
             username_suggestions = [username, first_name, last_name, email, "user"]
         else:
             username_suggestions = [first_name, last_name, email, "user"]
         user_username(user, generate_unique_username(username_suggestions))
         return user
     elif sociallogin.account.provider == "google":
         # if "screen_name" in sociallogin.account.extra_data.keys():
         # 	username = sociallogin.account.extra_data['screen_name']
         user_email(user, valid_email_or_none(email) or "")
         name_parts = (name or "").partition(" ")
         user_field(user, "first_name", first_name or name_parts[0])
         user_field(user, "last_name", last_name or name_parts[2])
         if username:
             username_suggestions = [username, first_name, last_name, email, "user"]
         else:
             username_suggestions = [first_name, last_name, email, "user"]
         user_username(user, generate_unique_username(username_suggestions))
         return user
     else:
         return super(SocialAccountAdapter, self).populate_user(request, sociallogin, data)
コード例 #46
0
ファイル: tasks.py プロジェクト: kili/dashboard
 def update_keystone_id(keystone_id, address):
     user = User.objects.get_by_natural_key(address)
     utils.user_field(user, 'keystone_id', keystone_id)
     user.save()
コード例 #47
0
ファイル: socialaccount.py プロジェクト: imclab/Franklin
	def populate_user(self, request, sociallogin, data):
		first_name = data.get('first_name')
		last_name = data.get('last_name')
		email = data.get('email')
		name = data.get('name')
		username = data.get('username')
		user = sociallogin.account.user
		print(sociallogin.account.provider)
		# TODO: Consider using the super class for the stuff that is not unique to facebook!
		if sociallogin.account.provider == 'facebook':
			user_email(user, valid_email_or_none(email) or '')
			name_parts = (name or '').partition(' ')
			user_field(user, 'first_name', first_name or name_parts[0])
			user_field(user, 'last_name', last_name or name_parts[2])
			# Save a good username
			if username:
				username_suggestions = [username, first_name, last_name, email, 'user']
			else:
				username_suggestions = [first_name, last_name, email, 'user']
			user_username(user, generate_unique_username(username_suggestions))
			return user
		elif sociallogin.account.provider == 'twitter':
			if "screen_name" in sociallogin.account.extra_data.keys():
				username = sociallogin.account.extra_data['screen_name']
			user_email(user, valid_email_or_none(email) or '')
			name_parts = (name or '').partition(' ')
			user_field(user, 'first_name', first_name or name_parts[0])
			user_field(user, 'last_name', last_name or name_parts[2])
			# Save a good username
			if username:
				username_suggestions = [username, first_name, last_name, email, 'user']
			else:
				username_suggestions = [first_name, last_name, email, 'user']
			user_username(user, generate_unique_username(username_suggestions))
			return user
		elif sociallogin.account.provider == 'google':
			#if "screen_name" in sociallogin.account.extra_data.keys():
			#	username = sociallogin.account.extra_data['screen_name']
			user_email(user, valid_email_or_none(email) or '')
			name_parts = (name or '').partition(' ')
			user_field(user, 'first_name', first_name or name_parts[0])
			user_field(user, 'last_name', last_name or name_parts[2])
			print("sociallogin.account.extra_data:", str(sociallogin.account.extra_data).encode('utf-8'))
			if username:
				username_suggestions = [username, first_name, last_name, email, 'user']
			else:
				username_suggestions = [first_name, last_name, email, 'user']
			user_username(user, generate_unique_username(username_suggestions))
			return user
		else:
			return super(SocialAccountAdapter, self).populate_user(request, sociallogin, data)