def authenticate(self, request, remote_user): if not remote_user: return user = None remote_user_data = json.loads( request.META.get('HTTP_REMOTE_USER_DATA')) user, created = UserModel.objects.get_or_create( email=remote_user_data['email']) user.username = remote_user user.first_name = remote_user_data['first_name'] user.last_name = remote_user_data['last_name'] if not hasattr(user, 'profile'): profile = UserProfile() profile.user = user else: profile = user.profile profile.avatar = remote_user_data['avatar'] profile.gender = remote_user_data['gender'] profile.uf = remote_user_data['uf'] profile.country = remote_user_data['country'] profile.birthdate = remote_user_data['birthdate'] profile.save() user.save() return user
def create(request): context = {} context['alert_count'] = Alerts.objects.filter(soft_delete=False).count() cleaner = forms.CharField() context['utc_offsets'] = utc_offsets #check if the current user is allowed to create new users this_profile = UserProfile.objects.get(user = request.user) if this_profile.oauth_scope == 'read write': context['can_edit'] = True else: return profiles(request) if request.method == "POST": user_profile_create_form = UserProfileEditForm(request.POST) user_create_form = UserEditForm(request.POST, instance=request.user) if user_create_form.is_valid() and user_profile_create_form.is_valid(): context['edit_msg'] = " New User successfully created." #get new django user from POST data username = cleaner.clean(request.POST['username']) first_name = user_create_form.cleaned_data.get("first_name") last_name = user_create_form.cleaned_data.get("last_name") email = user_create_form.cleaned_data.get("email") pw1 = cleaner.clean(request.POST['inputpassword1']) pw2 = cleaner.clean(request.POST['inputpassword2']) if pw1 == pw2: #passwords match so create new user new_user = User(username=username, first_name=first_name, last_name=last_name, email=email, ) new_user.set_password(pw1) new_user.save() oauth_scope = user_profile_create_form.cleaned_data.get("oauth_scope") utc_offset = user_profile_create_form.cleaned_data['utc_offset'] new_user_profile = UserProfile(user=new_user, oauth_scope=oauth_scope, utc_offset=utc_offset ) new_user_profile.save() return profiles(request) else: context['edit_msg'] = "Received data is not valid." return render(request, 'accounts/create_profile.html', context) return render(request, 'accounts/create_profile.html', context)
def create_user_profile(username, email, password, first_name, last_name, birthday, who_can_see_last_name, photo, city, state, country, location_view, gender, gender_view, age_view, web_site='', interests='', kind_books='', about_me='', active=True): user = User(username=username, email=email, password=make_password(password), first_name=first_name, last_name=last_name) user.save() user_profile = UserProfile(user=user, birthday=birthday, who_can_see_last_name=who_can_see_last_name, photo=photo, city=city, state=state, country=country, location_view=location_view, gender=gender, gender_view=gender_view, age_view=age_view, web_site=web_site, interests=interests, kind_books=kind_books, about_me=about_me, active=active) user_profile.save() email_setting = EmailSettings(user=user_profile) email_setting.save() feed_setting = FeedSetting(user=user_profile) feed_setting.save()
def get_autor_avatar(self): if self.avatar: return self.avatar profile = UserProfile.getUserProfile(self.autor) gravatar_url = profile.get_grevatar_src() self.avatar = gravatar_url return self.avatar
def process_request(self, request): # AuthenticationMiddleware is required so that request.user exists. if not hasattr(request, 'user'): raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") try: username = request.META[self.header] except KeyError: return # If the user is already authenticated and that user is the user we are # getting passed in the headers, then the correct user is already # persisted in the session and we don't need to continue. if request.user.is_authenticated: cleaned_username = self.clean_username(username, request) if request.user.get_username() == cleaned_username: return # We are seeing this user for the first time in this session, attempt # to authenticate the user. user = auth.authenticate(remote_user=username, request=request) if user: # User is valid. Set request.user and persist user in the session # by logging the user in. user_data = json.loads(request.META['HTTP_REMOTE_USER_DATA']) user.first_name = user_data['first_name'] user.last_name = user_data['last_name'] user.username = username if not hasattr(user, 'profile'): profile = UserProfile() profile.user = user else: profile = user.profile profile.avatar = user_data['avatar'] profile.gender = user_data['gender'] profile.uf = user_data['uf'] profile.country = user_data['country'] profile.birthdate = user_data['birthdate'] profile.save() user.save() request.user = user auth.login(request, user)
def create(self, request): username = request.POST['username'] users = User.objects.filter(username__iexact=username) if not users: password = request.POST['password'] email = request.POST['email'] user = User.objects.create_user(username, email, password) if user is not None: user.save() profile = UserProfile() profile.user = user profile.mobile = request.POST['mobile'] profile.save() return {'status':0, "message": "Register successfully."} else: return {'status':-3, "message": "Sorry, create user failed."} else: return {'status':-2, "message": "Sorry, user has been existed."}
def change(self, request, **kwargs): self.method_check(request, allowed=['post']) self.throttle_check(request) data = json.loads(request.body) UserModel = UserProfile() try: # token itself contains a hyphen so it's important to limit the split if kwargs.has_key('mail_token'): uidb64, token = kwargs.get('mail_token').split('-', 1) assert uidb64 is not None and token is not None uid = urlsafe_base64_decode(uidb64) user = UserModel._default_manager.get(pk=uid) except (AssertionError, TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): if data.get('new_password') == data.get('new_password_again'): user.set_password(data.get('new_password_again')) user.save() return self.create_response(request, {'message': 'Password reset successful.'}) return self.error_response(request, {'message': 'Error during password reset.'})
def profile(request, *args, **kwargs): profilepage = True # Create the basic forms which will be rendered in get requests user = request.user try: userprofile = UserProfile.objects.get(user = user) #profileform = ProfileForm(instance=userprofile, instance_user=user) except: userprofile = UserProfile(user = user) profileform = ProfileForm(instance=userprofile) if request.method == 'POST': postdata = request.POST.copy() if 'profileform' in postdata: # SIGNUP FORM profileform = ProfileForm(postdata, instance=userprofile) if profileform.is_valid(): # If the form is valid, save the user using the inbuilt function profileform.save() messages.success(request,'<strong>Done!</strong> Your account information was successfully saved !',extra_tags='alert-success') return HttpResponseRedirect(reverse('profile')) else: print "form errors" print profileform.errors if 'passwordform' in postdata: # SIGNUP FORM if postdata['password'] == postdata['confirm_password']: user.set_password(postdata['password']) user.save() print postdata['password'] else: print postdata['password'], postdata['confirm_password'] passwordform_errors = True show_passwordform = True if 'show_passwordform' in request.session: show_passwordform = request.session['show_passwordform'] del request.session['show_passwordform'] return render_to_response('pages/profile.html', locals(), context_instance= global_context(request))
def create(self, request): username = request.POST['username'] users = User.objects.filter(username__iexact=username) if not users: password = request.POST['password'] email = request.POST['email'] user = User.objects.create_user(username, email, password) if user is not None: user.save() profile = UserProfile() profile.user = user profile.mobile = request.POST['mobile'] profile.save() return {'status': 0, "message": "Register successfully."} else: return {'status': -3, "message": "Sorry, create user failed."} else: return {'status': -2, "message": "Sorry, user has been existed."}
try: cursor.execute("use pythonic") cursor.execute("ALTER table topic_topic AUTO_INCREMENT=19880929") conn.commit() except Exception, e: print e conn.rollback() finally: cursor.close() conn.close() #初始化用户 new_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') new_user.is_active = True new_user.save() new_profile = UserProfile(user=new_user,name=u'Eric',city=u'武汉') new_profile.save() second_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') second_user.is_active = True second_user.save() second_profile = UserProfile(user=second_user,name=u'Jack',city=u'北京') second_profile.save() third_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') third_user.is_active = True third_user.save() third_profile = UserProfile(user=third_user,name=u'Robbin',city=u'杭州') third_profile.save() #初始化类别
def save(request): if not request.user.is_staff and int(request.user.id) != int( request.POST['id']): raise PermissionDenied("User " + str(request.user.id) + " isn't staff") try: user = User.objects.get(id=request.POST['id']) except User.DoesNotExist: user = User() user.is_active = True user.username = request.POST['username'] user.email = request.POST['email'] if request.POST['password']: user.set_password(request.POST['password']) try: user.save() all_groups = [] for group in Group.objects.all(): all_groups.append(int(group.id)) post_groups = request.POST.getlist('groups[]') for idx, group in enumerate(post_groups): group = int(group) if group in all_groups: all_groups.remove(group) if group not in [ x.id for x in User.objects.get( id=request.POST['id']).groups.all() ]: #Groups.objects.filter(id__in=user.groups.all().values_list('id', flat=True))]: try: user.groups.add(group) except Exception as e: messages.error(request, str(e)) if len(all_groups) > 0: for group in all_groups: user.groups.remove(group) user.save() try: UserNotificationMethod.objects.filter(user=user).delete() except UserNotificationMethod.DoesNotExist: pass #Nothing to clear methods = request.POST.getlist('methods[]') for idx, item in enumerate(methods): method = UserNotificationMethod() method.method = item method.user = user method.position = idx + 1 method.save() if user.profile is None: profile = UserProfile() profile.user = user else: profile = user.profile profile.phone_number = request.POST['phone_number'] profile.pushover_user_key = request.POST['pushover_user_key'] profile.pushover_app_key = request.POST['pushover_app_key'] profile.slack_room_name = request.POST['slack_room_name'] profile.prowl_api_key = request.POST['prowl_api_key'] profile.prowl_application = request.POST['prowl_application'] profile.prowl_url = request.POST['prowl_url'] profile.rocket_webhook_url = request.POST['rocket_webhook_url'] profile.hipchat_room_name = request.POST['hipchat_room_name'] profile.hipchat_room_url = request.POST['hipchat_room_url'] profile.send_resolve_enabled = request.POST.get( "send_resolve_notification", "off") == "on" profile.save() return HttpResponseRedirect(reverse('openduty.users.list')) except IntegrityError: messages.error(request, 'Username already exists.') if int(request.POST['id']) > 0: return HttpResponseRedirect( reverse('openduty.users.edit', None, [str(request.POST['id'])])) else: return HttpResponseRedirect(reverse('openduty.users.new'))
try: cursor.execute("use pythonic") cursor.execute("ALTER table topic_topic AUTO_INCREMENT=19880929") conn.commit() except Exception, e: print e conn.rollback() finally: cursor.close() conn.close() #初始化用户 new_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') new_user.is_active = True new_user.save() new_profile = UserProfile(user=new_user,name=u'Eric',slug='eric',province="湖北",city=u'武汉') new_profile.save() second_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') second_user.is_active = True second_user.save() second_profile = UserProfile(user=second_user,name=u'Jack',slug='jack',province="北京",city=u'东城') second_profile.save() third_user = User.objects.create_user(username='******',email='*****@*****.**',password='******') third_user.is_active = True third_user.save() third_profile = UserProfile(user=third_user,name=u'Robbin',slug='robbin',province="浙江",city=u'杭州') third_profile.save() fourth_user = User.objects.create_user(username='******',email='*****@*****.**',password='******')
gravatar_url = ''.join(['http://www.gravatar.com/avatar/',avatar_name, '?s=48&d=404']) res_name = '%s-normal.%s' % (avatar_name, AVATAR_SAVE_FORMAT) res_path = os.path.join(AVATAR_DIR, res_name) req = urllib2.Request(gravatar_url) try: urllib2.urlopen(req) except urllib2.HTTPError, e: new_profile = UserProfile(user=new_user,name=data['name'],slug=data['slug'].lower(),province=data['province'],city=data['city']) pass else: urlretrieve(gravatar_url,res_path) gravatar_url = ''.join(['http://www.gravatar.com/avatar/',avatar_name, '?s=100&d=404']) res_name2 = '%s-large.%s' % (avatar_name, AVATAR_SAVE_FORMAT) res_path = os.path.join(AVATAR_DIR, res_name2) urlretrieve(gravatar_url,res_path) new_profile = UserProfile(user=new_user,name=data['name'],slug=data['slug'].lower(),province=data['province'],city=data['city'],avatar=res_name,photo=res_name2) try: new_user.save() new_profile.save() return HttpResponseRedirect('/accounts/active/%s/not_active' % new_user.get_profile().slug) except Exception,e: messages.error(request,'服务器出现错误:%s' %e) return render(request,'register.html',{"form":form,"zen":zen}) @csrf_protect def login(request): if request.user.is_authenticated(): return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) if request.method == 'GET': referer = request.META.get('HTTP_REFERER','/') if 'accounts' in str(referer) or 'notice' in str(referer) or 'message' in str(referer) or 'admin' in str(referer):