def register(params, login=True, commit=True): """ Create / register a user. """ if UserQueries.get_by_login(params.get("username", "")): raise UserServicesException( 'User with given username exists already.') user = User() model_fields = get_fields(User) # apply all fields to object. set_fields_from_dict(user, params, model_fields) user.login = params.get("username") user.password = generate_password_hash(params.get("password")) if commit: db.session.add(user) db.session.commit() if login: login_user(user) return user
def register(params, login=True, commit=True): """ Create / register a user. """ if UserQueries.get_by_login(params.get("username", "")): raise UserServicesException('User with given username exists already.') user = User() model_fields = get_fields(User) # apply all fields to object. set_fields_from_dict(user, params, model_fields) user.login=params.get("username") user.password=generate_password_hash(params.get("password")) if commit: db.session.add(user) db.session.commit() if login: login_user(user) return user
def login(data): # Assign vars email = data["email"] password = data["password"] try: # Fetch user data if not (user := User.objects(email=email).get_not_trashed().first()): return err_resp( "ایمیل یا رمزعبور صحیح نمیباشد.", "credentials_mismatch", 401, ) elif user and user.check_password(password): user_info = user_schema.dump(user) access_token = create_access_token(identity=str(user.id)) refresh_token = create_refresh_token(identity=str(user.id)) resp = message(True, "ورود موفقیت آمیز.") resp["access_token"] = access_token resp["refresh_token"] = refresh_token resp["user"] = user_info return resp, 200
def landing(request): stats = cache.get("landing_stats") if not stats: stats = { "users": User.registered_members().count(), "countries": User.registered_members().values("country").annotate( total=Count("country")).order_by().count() + 1, } cache.set("landing_stats", stats, settings.LANDING_CACHE_TIMEOUT) return render(request, "landing.html", {"stats": stats})
def post(self): try: new_user = UserSchema(exclude=['role']).load(request.json).data except ValidationError as err: return err.messages, status.HTTP_400_BAD_REQUEST try: new_user = User(email=new_user['email'], password=new_user['password'], first_name=new_user['first_name'], last_name=new_user['last_name'], role_id=1) except KeyError: return {'error': "Missing required field"} db.session.add(new_user) try: db.session.commit() except IntegrityError as err: db.session.emarollback() response = {'error': 'Already exists.'} return response, status.HTTP_400_BAD_REQUEST session.permanent = True access_token = create_access_token(identity=new_user.user_id, expires_delta=False) session[AUTH_TOKEN_KEY] = access_token response_obj = jsonify({'message': 'Successfully registered.'}) response_obj.set_cookie("admin", str(False)) return make_response(response_obj, status.HTTP_200_OK)
def password_reset(username, code): """password_reset(str, str) -> returns template The view function allows the user to reset their forgotten password :params `username`: The user's username `code`: The forgotten code sent to the user email account :returns returns a template """ form, error = NewPasswordForm(), None user = User(username=username) if not user.Account.Password.is_forgotten_password_code_valid(code): abort(404) if form.validate_on_submit() and user.Account.Password.reset_password( form): user.Account.Password.email_user_about_password_change() return redirect(url_for('password_app.password_successful_changed')) return render_template('password/password_reset.html', form=form, error=error, username=username, code=code)
def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User() form.populate_obj(user) # we hash the users password to avoid saving it as plaintext in the db, # remove to use plain text: user.password = generate_password_hash(form.password.data) db.session.add(user) db.session.commit() login.login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(FAdminIndexView, self).index()
def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User() form.populate_obj(user) # we hash the users password to avoid saving it as plaintext in the db, # remove to use plain text: user.password = generate_password_hash(form.password.data) db.session.add(user) db.session.commit() login.login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' + url_for( '.login_view') + '">Click here to log in.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(FAdminIndexView, self).index()
def forgot(): """This view function allows the user to request for a password reset link""" form, msg = ForgottenPasswordForm(), '' if form.validate_on_submit(): user = User(email=form.email.data) if user.Account.Password.generate_forgotten_password_code(): user.Account.Password.email_user_forgotten_password_code_link() return redirect(url_for('password_app.reset_link_sent')) return render_template('password/forgot_password.html', form=form)
def run(self): prod = input("Is this a production seed? [yes/no]" + "\n") if str(prod).lower() == "yes" and not self.check_safe(): return bcrypt = Bcrypt(flask.current_app) db = SQLAlchemy(flask.current_app) # seed roles from users.models.role import Role admin_role = Role( name="administrator", display_name="Administrator", description="Can administrate site", ) db.session.add(admin_role) writer_role = Role(name="writer", display_name="Writer", description="Can write posts for site") db.session.add(writer_role) user_role = Role(name="user", display_name="User", description="Basic user") db.session.add(user_role) # seed user admin_username = flask.current_app.config["ADMIN_INIT_USERNAME"] admin_password = flask.current_app.config["ADMIN_INIT_PASSWORD"] admin_password_hashed = bcrypt.generate_password_hash( admin_password).decode("utf-8") admin_email = flask.current_app.config["ADMIN_INIT_EMAIL"] from users.models.user import User admin_user = User( username=admin_username, password=admin_password_hashed, email=admin_email, active=True, email_confirmed_at=datetime.datetime.now(), ) admin_user.roles.append(admin_role) admin_user.roles.append(writer_role) db.session.add(admin_user) db.session.commit()
def change_password(): """The view function allows the user to change their current password""" form, error = ChangePasswordForm(), None user = User(email=Session.lookup('email')) if form.validate_on_submit(): if user.Account.Password.change_old_password(form): user.Account.Password.email_user_about_password_change() Session.delete_login_credentials() return redirect( url_for('password_app.password_successful_changed')) return render_template('password/new_password.html', form=form)
def stats(request): achievements = Achievement.objects\ .annotate(user_count=Count('users'))\ .filter(is_visible=True)\ .filter(user_count__gt=0)\ .exclude(code__in=["old", "parliament_member"])\ .order_by('-user_count') latest_badges = UserBadge.objects\ .select_related("badge", "to_user")\ .order_by('-created_at')[:20] top_badges = list( filter( None.__ne__, [ User.registered_members().filter(id=to_user).first() for to_user, _ in UserBadge.objects.filter( created_at__gte=datetime.utcnow() - timedelta(days=150)). values_list("to_user").annotate( sum_price=Sum("badge__price_days")).order_by("-sum_price") [:7] # select more in case someone gets deleted ]))[:5] # filter None moderators = User.objects\ .filter(Q(roles__contains=[User.ROLE_MODERATOR]) | Q(roles__contains=[User.ROLE_GOD])) parliament = User.objects.filter( achievements__achievement_id="parliament_member") top_users = User.objects\ .filter( moderation_status=User.MODERATION_STATUS_APPROVED, membership_expires_at__gte=datetime.utcnow() + timedelta(days=70) )\ .order_by("-membership_expires_at")[:64] return render( request, "pages/stats.html", { "achievements": achievements, "latest_badges": latest_badges, "top_badges": top_badges, "top_users": top_users, "moderators": moderators, "parliament": parliament, })
def get(self, token): if current_user.is_authenticated: return redirect(url_for("main.index")) user = User.verify_token(token) if user is None: flash( "Invalid or expired password reset token. Request a new one below.", "warning", ) return redirect(url_for("users.reset_password_request")) else: new_token = user.generate_password_reset_token() return render_template("users/reset_password.html", token=new_token, title="Reset Password")
def get(self, token): if current_user.is_authenticated: return redirect(url_for("main.index")) user = User.verify_token(token) if user is None: flash( "Invalid or expired password reset token. Request a new one below.", "warning", ) return redirect(url_for("users.reset_password_request")) else: new_token = user.generate_password_reset_token() return render_template( "users/reset_password.html", token=new_token, title="Reset Password" )
def __add_user(data, is_superuser=False): # Required values email = data["email"] password = data["password"] date_joined = data["date_joined"] if type(date_joined) is str: date_joined = dateutil.parser.parse(date_joined) date_joined = date_joined.astimezone(timezone('UTC')) # Optional data_first_name = data.get("first_name") data_last_name = data.get("last_name") data_is_active = data.get("is_active") data_is_staff = data.get("is_staff") # Check if the email is taken if User.objects(email=email).first() is not None: return validation_error( False, {"email": ["این ایمیل قبلا ثبت شده است."]}), 422 try: new_user = User( first_name=data_first_name, last_name=data_last_name, date_joined=date_joined, email=email, is_active=data_is_active, is_staff=data_is_staff, is_superuser=is_superuser, ) new_user.set_password_hash(password) new_user.save() # Load the new user's info user_info = user_schema.dump(new_user) resp = message(True, "کاربر با موفقیت ایجاد شد.") resp["user"] = user_info return resp, 201 except Exception as error: current_app.logger.error(error) return internal_err_resp()
def get(self, token): if current_user.is_authenticated and current_user.email_confirmed: return redirect(url_for("main.index")) user = User.verify_token(token) if user is None: flash("Invalid or expired email confirmation token.", "danger") elif user.email_confirmed_at: flash("This user has already been verified.", "warning") else: user.active = True user.email_confirmed_at = datetime.datetime.now() db.session.commit() flash("Your email has been verified!", "success") return redirect(url_for("main.index"))
def save_new_user(self, form): user_role = Role.query.filter_by(name="user").first() hashed_password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") user = User( username=form.username.data, email=form.email.data, password=hashed_password, first_name=form.first_name.data, last_name=form.last_name.data, ) user.roles.append(user_role) db.session.add(user) db.session.commit() return user
def api_search_users(request): if request.method != "GET": raise Http404() prefix = request.GET.get("prefix", "") if len(prefix) < MIN_PREFIX_LENGTH or len(prefix) > MAX_PREFIX_LENGTH: return JsonResponse({ "users": [] }) suggested_users = User.registered_members().filter(slug__startswith=prefix)[:5] return JsonResponse({ "users": [{ "slug": user.slug, "full_name": user.full_name } for user in suggested_users], })
def post(self, token): if current_user.is_authenticated: return redirect(url_for("main.index")) user = User.verify_token(token) form = ResetPasswordForm() if form.validate_on_submit(): user.password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") db.session.commit() flash("Your password has been reset!", "success") return jsonify({"success": True}) else: errors = form.errors if user is None: errors["token"] = ["Invalid token."] return jsonify(errors=form.errors), 422
def post(self, token): if current_user.is_authenticated: return redirect(url_for("main.index")) user = User.verify_token(token) form = ResetPasswordForm() if form.validate_on_submit(): user.password = bcrypt.generate_password_hash(form.password.data).decode( "utf-8" ) db.session.commit() flash("Your password has been reset!", "success") return jsonify({"success": True}) else: errors = form.errors if user is None: errors["token"] = ["Invalid token."] return jsonify(errors=form.errors), 422
def login(): """Allows the user to login into the application""" form = _render_login_template() if request.method == 'POST' and form.validate_on_submit(): user = User() account_status = user.Account.Retrieve.get_account_status( form.email.data) if account_status != 'ACCOUNT_CONFIRMED': return redirect(url_for(_get_status(account_status))) elif not user.Account.Login.is_login_valid(form.email.data, form.password.data): return redirect(url_for('login_app.no_user')) user.Account.Login.set_login_sessions(form.email.data) user.Account.Login.login() return redirect(url_for('home_page_app.home_page')) return render_template('login/login.html', form=form)
def create(self, validated_data): # create and store the new user user = User(username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'], phone=validated_data['phone'], address=validated_data['address'], type_account=2) # set password hash user.set_password(validated_data['password']) user.save() # if the user admin add the of promo model then will be create if self.promo_data[0] in validated_data: Promo(user=user, **{k: validated_data[k] for k in self.promo_data}).save() return user
def delete_user_data(user: User): if user.deleted_at is None: # user changed his mind return old_slug = str(user.slug) # anonymize user user.slug = random_string(length=32) user.email = f"{user.slug}@deleted.com" user.is_email_unsubscribed = True user.is_email_verified = False user.moderation_status = User.MODERATION_STATUS_REJECTED user.full_name = "💀 Юзер Удалился" user.avatar = None user.company = None user.position = None user.city = None user.country = None user.geo = None user.bio = None user.contact = None user.email_digest_type = User.EMAIL_DIGEST_TYPE_NOPE user.telegram_id = None user.telegram_data = None user.membership_platform_data = None user.save() # delete intro Post.objects.filter(author=user, type=Post.TYPE_INTRO).delete() # delete draft and unpublished posts Post.objects.filter(author=user, is_visible=False).delete() # transfer visible post ownership to "@deleted" user deleted_user = User.objects.filter(slug=settings.DELETED_USERNAME).first() if deleted_user: Post.objects.filter(author=user, is_visible=True).update(author=deleted_user) # replace nickname in replies new_slug = str(user.slug) Comment.objects\ .filter(reply_to__isnull=False, text__contains=f"@{old_slug}")\ .update( text=Replace("text", Value(f"@{old_slug}"), Value(f"@{new_slug}")), html=None ) # drop related data UserAchievement.objects.filter(user=user).delete() UserTag.objects.filter(user=user).delete() UserExpertise.objects.filter(user=user).delete() Session.objects.filter(user=user).delete() Code.objects.filter(user=user).delete() PostBookmark.objects.filter(user=user).delete()
from users.models.user import User user = User()
def people(request): users = User.registered_members().order_by("-created_at").select_related( "geo") query = request.GET.get("query") if query: users = users.filter(index__index=SearchQuery(query, config="russian")) tags = request.GET.getlist("tags") if tags: users = users.filter(index__tags__contains=tags) country = request.GET.get("country") if country: users = users.filter(country=country) filters = request.GET.getlist("filters") if filters: if "faang" in filters: users = users.filter(company__in=[ "Facebook", "Apple", "Google", "Amazon", "Netflix", "Microsoft", "Фейсбук", "Гугл", "Амазон", "Нетфликс", "Майкрософт", "Микрософт" ]) if "same_city" in filters: users = users.filter(city=request.me.city) if "activity" in filters: users = users.filter(last_activity_at__gte=datetime.utcnow() - timedelta(days=30)) tags_with_stats = Tag.tags_with_stats() tag_stat_groups = group_by(tags_with_stats, "group", todict=True) tag_stat_groups.update({ "travel": [ tag for tag in tag_stat_groups[Tag.GROUP_CLUB] if tag.code in { "can_coffee", "can_city", "can_beer", "can_office", "can_sleep", } ], "grow": [ tag for tag in tag_stat_groups[Tag.GROUP_CLUB] if tag.code in { "can_advice", "can_project", "can_teach", "search_idea", "can_idea", "can_invest", "search_mentor", "can_mentor", "can_hobby" } ], "work": [ tag for tag in tag_stat_groups[Tag.GROUP_CLUB] if tag.code in { "can_refer", "search_employees", "search_job", "search_remote", "search_relocate" } ], }) active_countries = User.registered_members().filter(country__isnull=False)\ .values("country")\ .annotate(country_count=Count("country"))\ .order_by("-country_count") map_stat_groups = { "💼 Топ компаний": top(users, "company")[:5], "🏰 Города": top(users, "city")[:5], "🎬 Экспертиза": top(UserExpertise.objects.filter(user_id__in=[u.id for u in users]), "name")[:5], } return render( request, "users/people.html", { "people_query": { "query": query, "country": country, "tags": tags, "filters": filters, }, "users": users, "users_paginated": paginate(request, users, page_size=settings.PEOPLE_PAGE_SIZE), "tag_stat_groups": tag_stat_groups, "max_tag_user_count": max(tag.user_count for tag in tags_with_stats), "active_countries": active_countries, "map_stat_groups": map_stat_groups, })
def create_tables(): print('Creating tables...') db.create_all() if db.session.query(User).count() == 0: # create super user. test_user = User() test_user.login="******" test_user.first_name = "Joe" test_user.last_name = "Lucas" test_user.password=generate_password_hash("test") test_user.is_super = True db.session.add(test_user) db.session.commit() test_user = User() test_user.login="******" test_user.first_name = "Bob" test_user.last_name = "Average" test_user.password=generate_password_hash("test") test_user.is_super = False db.session.add(test_user) db.session.commit()
def delete_user_data(user: User): if user.deleted_at is None: # user changed his mind return # anonymize user user.slug = random_string(length=32) user.email = f"{user.slug}@deleted.com" user.is_email_unsubscribed = True user.is_email_verified = False user.moderation_status = User.MODERATION_STATUS_REJECTED user.full_name = "💀 Юзер Удалился" user.avatar = None user.company = None user.position = None user.city = None user.country = None user.geo = None user.bio = None user.contact = None user.email_digest_type = User.EMAIL_DIGEST_TYPE_NOPE user.telegram_id = None user.telegram_data = None user.membership_platform_data = None user.save() # delete intro Post.objects.filter(author=user, type=Post.TYPE_INTRO).delete() # delete draft posts Post.objects.filter(author=user, is_visible=False).delete() # drop related data UserAchievement.objects.filter(user=user).delete() UserTag.objects.filter(user=user).delete() UserExpertise.objects.filter(user=user).delete() Session.objects.filter(user=user).delete() Code.objects.filter(user=user).delete() PostBookmark.objects.filter(user=user).delete() # cancel stripe subscriptions if user.stripe_id: stripe_subscriptions = stripe.Subscription.list( customer=user.stripe_id, limit=100) subscription_ids = [s["id"] for s in stripe_subscriptions["data"]] for subscription_id in subscription_ids: try: stripe.Subscription.delete(subscription_id) except Exception: pass