UNPKG

strapi-to-lokalise-plugin

Version:

Preview and sync Lokalise translations from Strapi admin

91 lines (80 loc) 2.68 kB
'use strict'; /** * Policy to ensure user is authenticated admin * Compatible with both Strapi v4 and v5 * * This policy manually authenticates admin users when routes have auth: false */ module.exports = async (policyContext, config, { strapi }) => { const ctx = policyContext; // Check if user is already authenticated if (ctx.state.user && ctx.state.user.id) { return true; } // Extract token from Authorization header or cookie const authHeader = ctx.request.headers.authorization; let token = null; if (authHeader && authHeader.startsWith('Bearer ')) { token = authHeader.replace('Bearer ', ''); } else { const cookieHeader = ctx.request.headers.cookie || ''; const jwtMatch = cookieHeader.match(/jwtToken=([^;]+)/); token = jwtMatch ? jwtMatch[1] : ctx.cookies?.get('jwtToken'); } if (!token) { ctx.status = 401; ctx.body = { error: { status: 401, name: 'UnauthorizedError', message: 'Missing or invalid credentials', details: {}, }, }; return false; } try { // Try Strapi's admin auth service (works for both v4 and v5) const adminAuth = strapi.admin?.services?.auth || strapi.plugin('admin')?.services?.auth; if (adminAuth && typeof adminAuth.verify === 'function') { const decoded = await adminAuth.verify({ token }); if (decoded && decoded.id) { const adminUser = await strapi.db.query('admin::user').findOne({ id: decoded.id }); if (adminUser && adminUser.isActive !== false) { ctx.state.user = adminUser; return true; } } } else { // Fallback: Direct JWT verification (for Strapi v4) const jwt = require('jsonwebtoken'); const jwtSecret = strapi.config.get('admin.jwtSecret') || strapi.config.get('server.adminJwtSecret') || process.env.ADMIN_JWT_SECRET || process.env.JWT_SECRET; if (jwtSecret) { const decoded = jwt.verify(token, jwtSecret); if (decoded && decoded.id) { const adminUser = await strapi.db.query('admin::user').findOne({ id: decoded.id }); if (adminUser && adminUser.isActive !== false) { ctx.state.user = adminUser; return true; } } } } } catch (err) { // Token invalid or expired - continue to return false } // Authentication failed ctx.status = 401; ctx.body = { error: { status: 401, name: 'UnauthorizedError', message: 'Missing or invalid credentials', details: {}, }, }; return false; };