def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): new_user = user_form.save(commit=False) new_user.username = user_form.cleaned_data['email'] new_user.password = user_form.cleaned_data['password'] new_user.save() pf = Profile( user=new_user, middle_name=profile_form.cleaned_data.get('middle_name'), phone=profile_form.cleaned_data.get('phone')) pf.save() # new_user.profile.middle_name=profile_form.cleaned_data["middle_name"] new_user.groups.add(Group.objects.get(name='abiturient')) return render(request, 'main/register_done.html', {'new_user': new_user}) else: user_form = UserRegistrationForm() profile_form = ProfileForm() return render(request, 'main/authorization.html', { 'user_form': user_form, 'profile_form': profile_form })
def update_token(request): post_data = json.loads(request.body) code = post_data.get("code") user = post_data.get("user") obj_user = User.objects.get(pk=user.get("id")) try: profile = Profile.objects.get(pk=user.get("id")) except Profile.DoesNotExist: profile = Profile(user=obj_user) profile.save() if (profile.bsc_code != code): bsc_tokens = bsc_api.get_token(code) print(bsc_tokens) profile.bsc_code = code profile.bsc_token = bsc_tokens.get("access_token") profile.bsc_refresh_token = bsc_tokens.get("refresh_token") profile.expires_in = datetime.now() + timedelta( seconds=bsc_tokens.get("expires_in")) profile.save() user["bsc_token"] = profile.bsc_token user["bsc_refresh_token"] = profile.bsc_refresh_token user["email"] = obj_user.email user["expires_in"] = profile.expires_in.strftime('%Y-%m-%d %I:%M %p') return JsonResponse({"user": user})
def finalize(request): current_user = request.user update_user = UpdateUserForm() user_profile = UserProfileForm() if request.method == 'POST': update_user = UpdateUserForm(request.POST) if update_user.is_valid(): first_name = update_user.cleaned_data.get('first_name') last_name = update_user.cleaned_data.get('last_name') email = update_user.cleaned_data.get('email') user = User.objects.get(pk=current_user.id) user.first_name = first_name user.last_name = last_name user.email = email user.save() user_profile = UserProfileForm(request.POST, request.FILES) if user_profile.is_valid(): phone = user_profile.cleaned_data.get('phone') bio = user_profile.cleaned_data.get('bio') country = user_profile.cleaned_data.get('country') photo = request.FILES.get('photo') print(phone) Profile.save_profile(current_user, bio, phone, country, photo) return redirect('home') context = { 'user_profile': user_profile, 'update_user': update_user, 'user': current_user, } return render(request, 'accounts/finalize.html', context)
def handle(self, *arg, **kwargs): p_id = Profile.new_id(kwargs['user_name']) p = Profile.get_or_create(p_id) for k in ('user_name', 'email', 'display_name', 'bio', 'location'): setattr(p, k, kwargs[k]) p.save()
def save(self, commit=True): user = User.objects.create_user(**self.cleaned_data.pop('user')) self.instance = Profile(user=user, **self.cleaned_data) if commit: self.instance.save() return self.instance
def register(request): if request.method == "POST": email = request.POST["email"] username = request.POST["username"] password = request.POST["password"] confirmation = request.POST["confirmation"] f_name = request.POST["f_name"] l_name = request.POST["l_name"] try: User.objects.get(username=username) return HttpResponse("error") except: try: User.objects.get(email=email) return HttpResponse("same email") except: pass user = User.objects.create_user(username=username, email=email, password=password, first_name=f_name, last_name=l_name) user.save() user = User.objects.get(username=username) p = Profile( user_id=User.objects.get(username=username).id, description="", organization="", location="", website="", avatar= "https://iupac.org/wp-content/uploads/2018/05/default-avatar.png") p.save() Verify(user_id=user.id, code=0).save() code = Verify.objects.get(user_id=user.id, code=0).id send_mail( email, "Verify your account", f"Hello! Please click on this link to verify your email address: <a href='{BASE_URL}/auth/verify/{str(code)}'>{BASE_URL}/auth/verify/{str(code)}</a> Verification code: {str(code)}" ) return HttpResponse( "Your account is successfully created, but please check your email to verify your account." ) else: return render(request, "authenticate/register.html")
class SignUpForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField( label=_("Password"), widget=forms.PasswordInput, ) confirm_password = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, ) class Meta: model = Profile fields = ('first_name', 'last_name', 'avatar', 'email', 'password', 'confirm_password', 'wallpaper', 'birthday') def clean(self): user_fields = ('email', 'password', 'confirm_password') user_data = {f: self.cleaned_data.pop(f) for f in user_fields} try: validate_password(user_data['password']) except ValidationError as e: self.add_error('password', e) confirm_password = user_data.pop('confirm_password') if user_data['password'] != confirm_password: self.add_error( 'confirm_password', ValidationError(_("The two password fields didn't match."), 'password_mismatch') ) user = User(email=user_data['email']) try: user.validate_unique() except ValidationError as e: for field, er in e.error_dict.items(): self.add_error(field, er) return {'user': user_data, **self.cleaned_data} def _post_clean(self): pass def save(self, commit=True): user = User.objects.create_user(**self.cleaned_data.pop('user')) self.instance = Profile(user=user, **self.cleaned_data) if commit: self.instance.save() return self.instance
def register(request): """Page with registration form.""" grp = get_info(request) if request.user.is_authenticated(): auth_logout(request) error = '' username = '' email = '' if request.method == "POST": try: username = request.POST['Username'] email = request.POST['Email'] password = request.POST['Password'] pr = request.POST['Password_repeat'] em = re.compile( r'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,6}$') n = re.compile(r'^[a-zA-Z0-9_@+.-]+$') if username == '' or email == '' or password == '' or pr == '': raise Exception('Some of the fields are empty.') elif len(username) > 29: raise Exception('Username too long.') elif not n.match(username): raise Exception( 'Username contains unallowed characters (only alphanumeric, _, @, +, . and - are allowed)' ) elif not em.match(email): raise Exception('Email is not valid.') elif password != pr: raise Exception('Passwords do not match.') except Exception as ex: error = ex else: user = User.objects.create_user(username, email, password) prf = Profile(user=user, groupname='User', email_show='no', city_show='no', phone_show='no', about_show='no', city='', phone='', about='') prf.save() return HttpResponseRedirect(reverse('login')) return render(request, 'main/register.html', { 'error_message': error, 'username': username, 'email': email, 'group': grp })
def create_invited_user(self, inviter_id, username, name, sex, email, password, site, send_email=False): """ add by cyb: Create a new, active ``User``, generate a ``Profile`` and email the register success information to ``User`` . Unlike function create_inactive_user, no activation email, only the success email will be sent. """ new_user = User.objects.create_user(username, email, password) new_user.is_active = True new_user.save() user_profile = Profile() user_profile.name = name user_profile.user_id = new_user.pk user_profile.sex = sex user_profile.is_active = True user_profile.invite_num = 10 user_profile.save() #Due to syncronization issue between database master and slave, return both to prevent inconsistency # in querying new_profile.user return_value ={} return_value['user_profile'] = user_profile return_value['new_user'] = new_user return return_value
def save(self, commit=True): new_user = super(UserCreationForm, self).save(commit=False) password = self.cleaned_data['password1'] email = self.cleaned_data['email'] new_user.set_password(password) new_user.email = email new_profile = Profile(user=new_user, role=self.cleaned_data['role']) if commit: new_user.save() new_profile.user = new_user new_profile.save() return new_user
def register(request): form = UserCreationForm(request.POST or None) if request.POST: if form.is_valid(): user = form.save() profile = Profile() profile.user = user profile.save() return redirect('login') else: for error in form.errors.items(): messages.warning(request, error) context = {'form': form} return render(request, "main/register.html", context)
def _decorated(request, *args, **kwargs): #Check authorization if request.user.is_authenticated: profile = Profile.get_profile(request.user) if not profile: return redirect('finalize') return view_func(request,*args, **kwargs)
def register(request): if request.method == 'POST': mail = request.POST.get('username', None) if mail == None: mail = request.POST['mail'] name = request.POST.get('name', mail) job = request.POST.get('job', 'BUS') password = request.POST['password'] user = User.objects.create_user(mail, mail, password) user.first_name = name user.save() user = authenticate(username=mail, password=password) login(request, user) profile = Profile(user=user, name=name, job=job) profile.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) return render(request, 'register.html', {})
def activate_user(self, activation_key): """ Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, the activation key is reset to the string constant ``RegistrationProfile.ACTIVATED`` after successful activation. """ # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): try: profile = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not profile.activation_key_expired(): user = profile.user user.is_active = True user.save() profile.activation_key = self.model.ACTIVATED profile.save() user_profile = Profile(name=user.username) user_profile.user_id = user.pk user_profile.save() return user return False
def register(request): """Page with registration form.""" grp = get_info(request) if request.user.is_authenticated(): auth_logout(request) error = '' username = '' email = '' if request.method == "POST": try: username = request.POST['Username'] email = request.POST['Email'] password = request.POST['Password'] pr = request.POST['Password_repeat'] em = re.compile(r'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+\.[a-zA-Z]{2,6}$') n = re.compile(r'^[a-zA-Z0-9_@+.-]+$') if username == '' or email == '' or password == '' or pr == '': raise Exception('Some of the fields are empty.') elif len(username) > 29: raise Exception('Username too long.') elif not n.match(username): raise Exception('Username contains unallowed characters (only alphanumeric, _, @, +, . and - are allowed)') elif not em.match(email): raise Exception('Email is not valid.') elif password != pr: raise Exception('Passwords do not match.') except Exception as ex: error = ex else: user = User.objects.create_user(username, email, password) prf = Profile(user = user, groupname = 'User', email_show='no', city_show='no', phone_show='no', about_show='no', city='', phone='', about='') prf.save() return HttpResponseRedirect(reverse('login')) return render(request, 'main/register.html', { 'error_message':error, 'username':username, 'email':email, 'group':grp })
def handle(self, *arg, **kwargs): # Grab the profile for supplied user name p = Profile.view(PROFILES_BY_USER_NAME_VIEW, key=kwargs['user_name']).first() if not p: raise CommandError('No profile named %s found' % kwargs['user_name']) subs = FeedSubscription.view(FEEDSUBSCRIPTION_BY_PROFILE_ID_VIEW, key=p._id).all() for s in subs: self.fetchSubscription(s)
def signUp_view(request): username = request.POST["username"] password = request.POST["password"] email = request.POST["email"] firstname = request.POST["firstName"] lastname = request.POST["lastName"] user = authenticate(request, username=username, password=password) if user is None: if username is not None and password is not None and email is not None and firstname is not None and lastname is not None: newuser = User.objects.create_user( username=username, password=password, email=email, first_name=firstname, last_name=lastname) user = authenticate(request, username=username, password=password) profile = Profile(userid = user.id, username = user.username) profile.save() login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "main/signup.html", {"message": "Username already in use"})
def SignUp(request): message = [] if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') phone_number = form.validate_phone() email = form.validate_email() username = form.validate_username() password = form.validate_password() if not email: message.append("Email already registered!") elif not password: message.append("Passwords don't match!") elif not username: message.append("Username already registered!") elif not phone_number: message.append("Invalid phone number!") else: print("SUCCESS!!!!!!") form.save() user = authenticate(username=username, password=password) login(request, user) profile = Profile(email=email, first_name=first_name, last_name=last_name, phone_number=phone_number) profile.save() return redirect("/profile") else: form = SignUpForm() return render(request, "registration/signup.html", { "form": form, "heading": "Sign Up", "message": message })
def setUp(self): self.client = Client() # User().save() User.objects.create_user( username="******", password="******", email="*****@*****.**") u = User.objects.get(username="******") Profile(user_id=u.id, description="", organization="", location="", website="", avatar="").save() Verify(user_id=u.id, code=0).save()
def get_user_from_bsc(user): refresh_token = user.get("bsc_refresh_token") obj_user = User.objects.get(pk=user.get("id")) try: profile = Profile.objects.get(pk=user.get("id")) except Profile.DoesNotExist: profile = Profile(user=obj_user) profile.save() if (refresh_token): bsc_tokens = bsc_api.refresh_token(refresh_token) profile.bsc_token = bsc_tokens.get("access_token") profile.bsc_refresh_token = bsc_tokens.get("refresh_token") profile.expires_in = datetime.now() + timedelta( seconds=bsc_tokens.get("expires_in")) profile.save() user["bsc_token"] = profile.bsc_token user["bsc_refresh_token"] = profile.bsc_refresh_token user["email"] = obj_user.email user["expires_in"] = profile.expires_in.strftime('%Y-%m-%d %I:%M %p') return user
def profile_creation(username): form = ProfileForm() if form.validate_on_submit(): username = flask.session['user'] first_name = flask.session['first_name'] last_name = flask.session['last_name'] email = flask.session['email'] password = flask.session['password'] user = User(username=username, first_name=first_name, last_name=last_name, email=email, password=password) db.session.add(user) db.session.commit() user_id = user.id profile = Profile(weight=form.weight.data, height=form.height.data, goal=form.goal.data, age=form.age.data, gender=form.gender.data, location=form.location.data, quote=form.quote.data, user_id=user_id) db.session.add(profile) set_blank_macros(user_id) set_blank_schedule(user_id) db.session.commit() login_user(user) flash(f'You have successfully created your account!', 'success') return redirect(url_for('fitness_page')) return render_template('profile-creation.html', title="Create Your Profile", form=form)
def handle(self, *arg, **kwargs): # Grab the profile for supplied user name p = Profile.view(PROFILES_BY_USER_NAME_VIEW, key=kwargs['profile']).first() if not p: raise CommandError('No profile named %s found' % kwargs['profile']) sub = FeedSubscription.get_or_create('%s:%s' % ('FeedSubscription', kwargs['url'])) sub.feed_type = kwargs['type'] sub.profile_id = p._id sub.url = kwargs['url'] sub.link = kwargs['link'] sub.title = kwargs['title'] sub.save()
def update(self, instance, validated_data): profile_data = validated_data.pop('profile', None) obj = super(ProfileUserSerializer, self).update(instance, validated_data) if profile_data: if hasattr(instance, 'profile'): profile = instance.profile profile.info = profile_data.get('info') profile.first_name = profile_data.get('first_name') profile.second_name = profile_data.get('second_name') profile.daybirth = profile_data.get('daybirth') profile.sex = profile_data.get('sex') profile.number_phone = profile_data.get('number_phone') profile.save() else: Profile(user=instance) return obj
def test_forgot_password(self): tag = random_str() User.objects.create_user(username="******", password="******", email=f"5v6g6.{tag}@inbox.testmail.app") user = User.objects.get(username="******") Profile(user_id=user.id, description="", organization="", location="", website="", avatar="").save() rv = self.client.post("/auth/forgot-password/", data={"username": "******"}, follow=True) print(rv.content) r = requests.get( f"https://api.testmail.app/api/json?apikey={os.getenv('TESTMAIL_API')}&namespace=5v6g6&pretty=true&livequery=true&limit=1&tag={tag}&headers=true" ).json() code = r["emails"][0]["html"].split("Forgot Password Code: ")[1] print(code) rv = self.client.post(f"/auth/forgot-password/{code}/", {"password": "******"}, follow=True) assert b"Login" in rv.content rv = self.client.post(f"/auth/login/", { "username": "******", "password": "******", "deviceid": "" }, follow=True) assert b"Repositories" in rv.content
def handle(self, *arg, **kwargs): if len(arg) < 1: raise CommandError('OPML filename required') # Grab the profile for supplied user name p = Profile.view(PROFILES_BY_USER_NAME_VIEW, key=kwargs['user_name']).first() if not p: raise CommandError('No profile named %s found' % kwargs['user_name']) # Look up subscriptions for profile. subs = FeedSubscription.view(FEEDSUBSCRIPTION_BY_PROFILE_ID_VIEW, key=p._id).all() subs_by_url = dict((s.url, s) for s in subs) with open(arg[0]) as fin: entries = opml.get_subscriptions(fin) for entry in entries: url = unicode(entry['xmlurl']) if url in subs_by_url: sub = subs_by_url[url] print "Updating %s" % entry['title'] else: sub = FeedSubscription.get_or_create() print "Creating %s" % entry['title'] sub.profile_id = p._id sub.feed_type = 'rss' sub.url = url sub.link = entry['url'] sub.title = entry['title'] sub.parents = [x['title'] for x in entry['parents']] sub.save()
def user_register_plan(request, plan_url): "plan_url of 'free' means free plan" if request.user.is_authenticated(): return change_plan(request, plan_url) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): plan_id = 0 plan = None # create the user user = User.objects.create_user(form.cleaned_data.get('username'), form.cleaned_data.get('email'), form.cleaned_data.get('password')) user.save() # create a band band = Band() band.title = form.cleaned_data.get('artist_name') band.total_space = settings.BAND_INIT_SPACE band.save() # create a profile profile = Profile() profile.user = user profile.solo_band = band profile.activated = False profile.activate_code = create_hash(32) profile.logon_count = 0 profile.band_count_limit = settings.FREE_BAND_LIMIT profile.save() # make them a manager manager = BandMember() manager.user = user manager.band = band manager.role = BandMember.MANAGER manager.save() # send an activation email subject = design.account_confirmation context = Context({ 'user': user, 'activate_url': request.build_absolute_uri(reverse('confirm', args=[user.username, profile.activate_code])), 'host': request.get_host(), }) message_txt = get_template('email/activation.txt').render(context) message_html = get_template('email/activation.html').render(context) send_html_mail(subject, message_txt, message_html, [user.email]) return HttpResponseRedirect(reverse("register_pending")) else: try: plan = AccountPlan.objects.get(url=plan_url) plan_id = plan.id except AccountPlan.DoesNotExist: plan = None plan_id = 0 form = RegisterForm(initial={'plan': plan_id}) return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() prof = Profile() prof.organization_user = new_user prof.name = user_form.cleaned_data["organization_name"] prof.organization_slug = slugify( user_form.cleaned_data["organization_name"]) prof.ein_number = user_form.cleaned_data["ein_number"] prof.about = user_form.cleaned_data["about"] prof.organization_city = user_form.cleaned_data[ "organization_city"] prof.organization_country = user_form.cleaned_data[ "organization_country"] prof.organization_contact_email = user_form.cleaned_data[ "organization_contact_email"] prof.organization_mission = user_form.cleaned_data[ "organization_mission"] prof.organization_primary_objective1 = user_form.cleaned_data[ "organization_primary_objective1"] prof.organization_primary_objective2 = user_form.cleaned_data[ "organization_primary_objective2"] prof.organization_primary_objective3 = user_form.cleaned_data[ "organization_primary_objective3"] prof.save() return HttpResponse("Registration Done") else: user_form = UserRegistrationForm() context = {'user_form': user_form} return render(request, 'main/register.html', context=context)
def unify_names(sender: Profile, instance: Profile, **kwargs): instance.lastname = unify_fio(instance.lastname) instance.firstname = unify_fio(instance.firstname) instance.middlename = unify_fio(instance.middlename)
def handle(self, *arg, **kwargs): # Grab the profile for supplied user name p = Profile.view(PROFILES_BY_USER_NAME_VIEW, key=kwargs['user_name']).first() if not p: raise CommandError('No profile named %s found' % kwargs['user_name']) # Look up subscriptions for profile. subs = FeedSubscription.view(FEEDSUBSCRIPTION_BY_PROFILE_ID_VIEW, key=p._id).all() subs_by_url = dict((s.url, s) for s in subs) uid = kwargs['stream'] if uid.startswith('https://plus.google.com'): uid = uid.split('/')[3] lookup_url = LOOKUP_URL.format(uid) r = requests.get(lookup_url) ids = [line.split('"')[1] for line in r.content.split("\n") if line.startswith(',[[,,')] urls = [STREAM_URL.format(id, kwargs['apikey']) for id in ids] open(kwargs['output'], 'w').write("\n".join(urls)) for url in urls: r = requests.get(url) print "(%s) %s" % (r.status_code, url) if 200 != r.status_code: continue now = int(time.time() * 1000) stream = json.loads(r.content) if url in subs_by_url: sub = subs_by_url[url] print "Updating %s" % url else: sub = FeedSubscription.get_or_create() print "Creating %s" % url sub.profile_id = p._id sub.feed_type = 'as-json' sub.url = url sub.title = stream['title'] sub.link = len(stream['items']) and stream['items'][0]['actor']['url'] or url sub.last_fetch_time = now sub.save() hr_id = HttpResource.new_id(url) hr = HttpResource.get_or_create(hr_id) hr.url = url hr.status = r.status_code hr.headers = r.headers hr.last_fetch_time = now hr.save() hr.put_attachment(r.content, 'body', hr.headers['content-type'])
def user_register_plan(request, plan_url): "plan_url of 'free' means free plan" if request.user.is_authenticated(): return change_plan(request, plan_url) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): plan_id = 0 plan = None # create the user user = User.objects.create_user(form.cleaned_data.get('username'), form.cleaned_data.get('email'), form.cleaned_data.get('password')) user.save() # create a band band = Band() band.title = form.cleaned_data.get('artist_name') band.total_space = settings.BAND_INIT_SPACE band.save() # create a profile profile = Profile() profile.user = user profile.solo_band = band profile.activated = False profile.activate_code = create_hash(32) profile.logon_count = 0 profile.band_count_limit = settings.FREE_BAND_LIMIT profile.save() # make them a manager manager = BandMember() manager.user = user manager.band = band manager.role = BandMember.MANAGER manager.save() # send an activation email subject = design.account_confirmation context = Context({ 'user': user, 'activate_url': request.build_absolute_uri( reverse('confirm', args=[user.username, profile.activate_code])), 'host': request.get_host(), }) message_txt = get_template('email/activation.txt').render(context) message_html = get_template('email/activation.html').render( context) send_html_mail(subject, message_txt, message_html, [user.email]) return HttpResponseRedirect(reverse("register_pending")) else: try: plan = AccountPlan.objects.get(url=plan_url) plan_id = plan.id except AccountPlan.DoesNotExist: plan = None plan_id = 0 form = RegisterForm(initial={'plan': plan_id}) return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
def save(self, profile_callback=None): user = super(RegistrationFormProfile, self).save(profile_callback) profile = Profile(user=user) profile.save() return user