Skip to content

Feat/login - #15

Open
ananastii wants to merge 2 commits into
mainfrom
feat/login
Open

Feat/login#15
ananastii wants to merge 2 commits into
mainfrom
feat/login

Conversation

@ananastii

@ananastii ananastii commented Jul 22, 2026

Copy link
Copy Markdown

Нужно добавить плагин sysblok-headless-auth.php в код сайта и настроить, как описано в README.md
.

Директория:
sysblok-headless-auth/sysblok-headless-auth.php

Также в readme плагина - какие изменения нужно внести в .env.local и как это работает. Спасибо Claude!

Страница логина открывается на странице /login.
У залогиненного юзера под шапкой появляется узкая плашка с ником и кнопкой logout (не стала впихивать в шапку).

@ananastii
ananastii requested a review from Feretj July 22, 2026 14:45
@Feretj

Feretj commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator

Надо добавить в app/posts/[slug]/page.tsx запросы getPostBySlug (getPostData) делали запрос со status: 'any' если пользователь авторизован. Можем это вынести в отдельную задачу вместе с редиректом на превью в Next из редактора админки. Но точно надо проверить что REST запросы делаются с авторизацией

})

if (!verifyResponse.ok) {
const error = await verifyResponse.json().catch(() => ({}))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

catch здесь на случай если пустой body пришел?

// Invalidate the token on WordPress side
if (session.token && wpBaseUrl && authSecret) {
try {
await fetch(`${wpBaseUrl}/wp-json/sysblok/v1/auth/logout`, {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Используешь fetch с wpBaseUrl и authSecret второй раз. Сделай функцию wordpressAuthFetch или wordpressPostFetch. Можно в auth.ts чтоб разделить с клиенской логикой в wordpress.ts

Comment thread app/login/page.tsx

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В реальности наши редакторы будут заходить в админку через Next и из админки на превью обратно. Чтоб не делать лишнего действия можно сразу редиректить на страницу логина wordpress и оставить только отображение ошибки.

Comment thread app/globals.css
}

/* =========================================
Auth bar (shown below nav when logged in)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auth bar будет только редакторам отображаться, давай все стили сделаем через tailwind css в самой компоненте

@@ -0,0 +1,11 @@
'use client'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может тогда сделать весь AuthBar клиенской компонентой, чтоб серверную часть не затрагивало

Comment thread proxy.ts
*
* If the cookie is missing on a protected route, redirects to /login.
*/
export function proxy(request: NextRequest) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот прокси не нужен. Сейчас на проде если юзер не залогинен, приватные страницы просто отдают 404, давай так и оставим.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай добавим изменение ссылки превью через фильтр preview_post_link, может с чекбоксом для включения. Можно в отдельную задачу выделить.

* Description: Authentication bridge for headless Next.js frontend. Handles login redirect, session tokens, and REST API authentication.
* Version: 1.0.0
* Author: Sysblok
* License: GPLv2 or later

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай оставим GPLv2 и добавь LICENSE файл

register_setting(
'sysblok_headless_auth_group',
$this->option_name,
array($this, 'sanitize_settings')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно добавить дефолтное значение которое берется из переменных окружения.

Suggested change
array($this, 'sanitize_settings')
array(
'type' => 'array',
'sanitize_callback' => array($this, 'sanitize_settings'),
'default' => array(
'allowed_redirect_origin' => getenv('NEXT_PUBLIC_URL') || 'http://localhost:3000',
'auth_shared_secret' => getenv('WP_AUTH_SHARED_SECRET') || '',
'token_ttl' => 86400
)
)

Еще можно разделить значения в разные register_setting

* Check for Bearer token in REST API requests and set the current user.
* This makes WordPress permission checks work automatically.
*/
public function authenticate_rest_request($user_id) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Попробовал проверить на личном посте по ссылке: http://localhost:3000/posts/openai-otkatila-obnovlenie-gpt-4o-posle-zhalob

Получил 404 потому что статус "private" не отдается. Добавил в getPostBySlug параметр status: 'any'. Запрос вернулся с ошибкой 400, параметр status с таким значением запрещен, так же как если без аторизации сделать запрос.

Image Image

Comment thread .env.example
SSL_CERTS=./certificates

# Auth: WordPress login URL (change if using a custom login URL plugin)
NEXT_PUBLIC_WP_LOGIN_URL="https://sysblok.ru/wp-login.php"

@Feretj Feretj Aug 16, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай назовем WORDPRESS_LOGIN_SLUG, я в плагине смены сcылки логина переиспользую. Ненадо NEXT_PUBLIC чтоб на клиенте не было нашей секретной ссылки. Конечную ссылку тогда получай так: process.env.NEXT_PUBLIC_WORDPRESS_URL + '/' + process.env.WORDPRESS_LOGIN_SLUG

Suggested change
NEXT_PUBLIC_WP_LOGIN_URL="https://sysblok.ru/wp-login.php"
WORDPRESS_LOGIN_SLUG="wp-login.php"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants