import Planka upstream

This commit is contained in:
xiaojibeier
2026-07-18 11:48:22 +08:00
commit c26fd3b190
1564 changed files with 214813 additions and 0 deletions
@@ -0,0 +1,234 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
/**
* @swagger
* /access-tokens/accept-terms:
* post:
* summary: Accept terms and conditions
* description: Accept terms during the authentication flow. Converts the pending token to an access token.
* tags:
* - Access Tokens
* operationId: acceptTerms
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - pendingToken
* - signature
* properties:
* pendingToken:
* type: string
* maxLength: 1024
* description: Pending token received from the authentication flow
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ4...
* signature:
* type: string
* minLength: 64
* maxLength: 64
* description: Terms signature hash
* example: 940226c4c41f51afe3980ceb63704e752636526f4c52a4ea579e85b247493d94
* initialLanguage:
* type: string
* enum: [ar-YE, bg-BG, ca-ES, cs-CZ, da-DK, de-DE, el-GR, en-GB, en-US, es-ES, et-EE, fa-IR, fi-FI, fr-FR, hu-HU, id-ID, it-IT, ja-JP, ko-KR, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sr-Cyrl-RS, sr-Latn-RS, sv-SE, tr-TR, uk-UA, uz-UZ, vi-VN, zh-CN, zh-TW]
* nullable: true
* description: Preferred language for user interface and notifications (used only if user language is not set)
* example: en-US
* responses:
* 200:
* description: Terms accepted successfully
* content:
* application/json:
* schema:
* type: object
* required:
* - item
* properties:
* item:
* type: string
* description: Access token for API authentication
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ5...
* 400:
* $ref: '#/components/responses/ValidationError'
* 401:
* description: Invalid pending token
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_UNAUTHORIZED
* message:
* type: string
* description: Error message
* example: Invalid pending token
* 403:
* description: Authentication restriction
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_FORBIDDEN
* message:
* type: string
* enum:
* - Invalid signature
* - Admin login required to initialize instance
* description: Specific error message
* example: Invalid signature
* security: []
*/
const { getRemoteAddress } = require('../../../utils/remote-address');
const { AccessTokenSteps } = require('../../../constants');
const Errors = {
INVALID_PENDING_TOKEN: {
invalidPendingToken: 'Invalid pending token',
},
INVALID_SIGNATURE: {
invalidSignature: 'Invalid signature',
},
ADMIN_LOGIN_REQUIRED_TO_INITIALIZE_INSTANCE: {
adminLoginRequiredToInitializeInstance: 'Admin login required to initialize instance',
},
};
module.exports = {
inputs: {
pendingToken: {
type: 'string',
maxLength: 1024,
required: true,
},
signature: {
type: 'string',
minLength: 64,
maxLength: 64,
required: true,
},
initialLanguage: {
type: 'string',
isIn: User.LANGUAGES,
allowNull: true,
},
},
exits: {
invalidPendingToken: {
responseType: 'unauthorized',
},
invalidSignature: {
responseType: 'forbidden',
},
adminLoginRequiredToInitializeInstance: {
responseType: 'forbidden',
},
},
async fn(inputs) {
const remoteAddress = getRemoteAddress(this.req);
const { httpOnlyToken } = this.req.cookies;
try {
payload = sails.helpers.utils.verifyJwtToken(inputs.pendingToken);
} catch (error) {
if (error.raw.name === 'TokenExpiredError') {
throw Errors.INVALID_PENDING_TOKEN;
}
sails.log.warn(`Invalid pending token! (IP: ${remoteAddress})`);
throw Errors.INVALID_PENDING_TOKEN;
}
if (payload.subject !== AccessTokenSteps.ACCEPT_TERMS) {
throw Errors.INVALID_PENDING_TOKEN;
}
let session = await Session.qm.getOneUndeletedByPendingToken(inputs.pendingToken);
if (!session) {
sails.log.warn(`Invalid pending token! (IP: ${remoteAddress})`);
throw Errors.INVALID_PENDING_TOKEN;
}
if (session.httpOnlyToken && httpOnlyToken !== session.httpOnlyToken) {
throw Errors.INVALID_PENDING_TOKEN;
}
if (!sails.hooks.terms.isSignatureValid(inputs.signature)) {
throw Errors.INVALID_SIGNATURE;
}
let user = await User.qm.getOneById(session.userId, {
withDeactivated: false,
});
if (!user) {
throw Errors.INVALID_PENDING_TOKEN; // TODO: introduce separate error?
}
const values = {
termsSignature: inputs.signature,
termsAcceptedAt: new Date().toISOString(),
};
if (!user.language && inputs.initialLanguage) {
values.language = inputs.initialLanguage;
}
({ user } = await User.qm.updateOne(user.id, values));
const internalConfig = await InternalConfig.qm.getOneMain();
if (!internalConfig.isInitialized) {
if (user.role === User.Roles.ADMIN) {
await InternalConfig.qm.updateOneMain({
isInitialized: true,
});
} else {
throw Errors.ADMIN_LOGIN_REQUIRED_TO_INITIALIZE_INSTANCE;
}
}
const { token: accessToken, payload: accessTokenPayload } = sails.helpers.utils.createJwtToken(
user.id,
);
session = await Session.qm.updateOne(session.id, {
accessToken,
pendingToken: null,
});
if (session.httpOnlyToken && !this.req.isSocket) {
sails.helpers.utils.setHttpOnlyTokenCookie(
session.httpOnlyToken,
accessTokenPayload,
this.res,
);
}
return {
item: accessToken,
};
},
};
+217
View File
@@ -0,0 +1,217 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
/**
* @swagger
* /access-tokens:
* post:
* summary: User login
* description: Authenticates a user using email/username and password. Returns an access token for API authentication.
* tags:
* - Access Tokens
* operationId: createAccessToken
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - emailOrUsername
* - password
* properties:
* emailOrUsername:
* type: string
* maxLength: 256
* description: Email address or username of the user
* example: john.doe@example.com
* password:
* type: string
* maxLength: 256
* description: Password of the user
* example: SecurePassword123!
* withHttpOnlyToken:
* type: boolean
* description: Whether to include an HTTP-only authentication cookie
* example: true
* responses:
* 200:
* description: Login successful
* content:
* application/json:
* schema:
* type: object
* required:
* - item
* properties:
* item:
* type: string
* description: Access token for API authentication
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ4...
* headers:
* Set-Cookie:
* description: HTTP-only authentication cookie (if `withHttpOnlyToken` is true)
* schema:
* type: string
* example: httpOnlyToken=29aa3e38-8d24-4029-9743-9cbcf0a0dd5c; HttpOnly; Secure; SameSite=Strict
* 400:
* $ref: '#/components/responses/ValidationError'
* 401:
* description: Invalid credentials
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_UNAUTHORIZED
* message:
* type: string
* enum:
* - Invalid credentials
* - Invalid email or username
* - Invalid password
* description: Specific error message
* example: Invalid credentials
* 403:
* description: Authentication restriction
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_FORBIDDEN
* message:
* type: string
* enum:
* - Use single sign-on
* - Terms acceptance required
* - Admin login required to initialize instance
* description: Specific error message
* example: Use single sign-on
* security: []
*/
const bcrypt = require('bcrypt');
const { isEmailOrUsername } = require('../../../utils/validators');
const { getRemoteAddress } = require('../../../utils/remote-address');
const Errors = {
INVALID_CREDENTIALS: {
invalidCredentials: 'Invalid credentials',
},
INVALID_EMAIL_OR_USERNAME: {
invalidEmailOrUsername: 'Invalid email or username',
},
INVALID_PASSWORD: {
invalidPassword: 'Invalid password',
},
USE_SINGLE_SIGN_ON: {
useSingleSignOn: 'Use single sign-on',
},
TERMS_ACCEPTANCE_REQUIRED: {
termsAcceptanceRequired: 'Terms acceptance required',
},
};
module.exports = {
inputs: {
emailOrUsername: {
type: 'string',
maxLength: 256,
custom: isEmailOrUsername,
required: true,
},
password: {
type: 'string',
maxLength: 256,
required: true,
},
withHttpOnlyToken: {
type: 'boolean',
},
},
exits: {
invalidCredentials: {
responseType: 'unauthorized',
},
invalidEmailOrUsername: {
responseType: 'unauthorized',
},
invalidPassword: {
responseType: 'unauthorized',
},
useSingleSignOn: {
responseType: 'forbidden',
},
termsAcceptanceRequired: {
responseType: 'forbidden',
},
adminLoginRequiredToInitializeInstance: {
responseType: 'forbidden',
},
},
async fn(inputs) {
if (sails.config.custom.oidcEnforced) {
throw Errors.USE_SINGLE_SIGN_ON;
}
const remoteAddress = getRemoteAddress(this.req);
const user = await User.qm.getOneActiveByEmailOrUsername(inputs.emailOrUsername);
if (!user) {
sails.log.warn(
`Invalid email or username: "${inputs.emailOrUsername}"! (IP: ${remoteAddress})`,
);
throw sails.config.custom.showDetailedAuthErrors
? Errors.INVALID_EMAIL_OR_USERNAME
: Errors.INVALID_CREDENTIALS;
}
if (user.isSsoUser) {
throw Errors.USE_SINGLE_SIGN_ON;
}
const isPasswordValid = await bcrypt.compare(inputs.password, user.password);
if (!isPasswordValid) {
sails.log.warn(`Invalid password! (IP: ${remoteAddress})`);
throw sails.config.custom.showDetailedAuthErrors
? Errors.INVALID_PASSWORD
: Errors.INVALID_CREDENTIALS;
}
return sails.helpers.accessTokens.handleSteps
.with({
user,
remoteAddress,
request: this.req,
response: this.res,
withHttpOnlyToken: inputs.withHttpOnlyToken,
})
.intercept('adminLoginRequiredToInitializeInstance', (error) => ({
adminLoginRequiredToInitializeInstance: error.raw,
}))
.intercept('termsAcceptanceRequired', (error) => ({
termsAcceptanceRequired: error.raw,
}));
},
};
@@ -0,0 +1,223 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
const Errors = {
NOT_ENOUGH_RIGHTS: {
notEnoughRights: 'Not enough rights',
},
};
module.exports = {
inputs: {
code: {
type: 'string',
maxLength: 2048,
required: true,
},
nonce: {
type: 'string',
maxLength: 1024,
required: true,
},
},
exits: {
notEnoughRights: {
responseType: 'forbidden',
},
},
async fn(inputs) {
if (!sails.config.custom.oidcDebug) {
throw Errors.NOT_ENOUGH_RIGHTS;
}
const logs = ['🔐 Starting OIDC debug flow...', ''];
const client = await sails.hooks.oidc.getClient();
if (!client) {
logs.push('❌ OIDC client is not initialized.');
logs.push('💡 Hint: Check your OIDC issuer and client configuration.');
return {
item: null,
included: {
logs,
},
};
}
let tokenSet;
try {
logs.push('🔄 Exchanging authorization code...');
if (sails.config.custom.oidcUseOauthCallback) {
tokenSet = await client.oauthCallback(
sails.config.custom.oidcRedirectUri,
{
iss: sails.config.custom.oidcIssuer,
code: inputs.code,
},
{ nonce: inputs.nonce },
);
} else {
tokenSet = await client.callback(
sails.config.custom.oidcRedirectUri,
{
iss: sails.config.custom.oidcIssuer,
code: inputs.code,
},
{ nonce: inputs.nonce },
);
}
logs.push('✅ Authorization code exchanged successfully.', '');
} catch (error) {
logs.push('❌ Failed to exchange authorization code.');
logs.push(`💬 Reason: ${error.message || error.toString()}`);
logs.push('💡 Hint: Check redirect URI, client secret, and nonce handling.');
return {
item: null,
included: {
logs,
},
};
}
if (sails.config.custom.oidcClaimsSource === 'id_token') {
logs.push('📥 Extracting claims from ID token...');
try {
claims = tokenSet.claims();
logs.push('✅ Claims extracted successfully.', '');
} catch (error) {
logs.push('❌ Failed to extract user claims.');
logs.push(`💬 Reason: ${error.message || error.toString()}`);
return {
item: null,
included: {
logs,
},
};
}
} else {
logs.push('📥 Fetching claims from userinfo endpoint...');
try {
claims = await client.userinfo(tokenSet);
logs.push('✅ Claims fetched successfully.', '');
} catch (error) {
logs.push('❌ Failed to fetch user claims.');
if (error instanceof SyntaxError && error.message.includes('Unexpected token e in JSON')) {
logs.push('💬 Reason: Userinfo response is signed or not JSON.');
logs.push(
'💡 Hint: Try configuring userinfo signed response algorithm or switch to ID token claims.',
);
} else {
logs.push(`💬 Reason: ${error.message || error.toString()}`);
}
return {
item: null,
included: {
logs,
},
};
}
}
logs.push('📦 Raw claims received:', JSON.stringify(claims, null, 2), '');
logs.push('🧩 Evaluating claim mappings...', '');
const mappings = {
email: {
attribute: sails.config.custom.oidcEmailAttribute,
value: _.get(claims, sails.config.custom.oidcEmailAttribute),
},
name: {
attribute: sails.config.custom.oidcNameAttribute,
value: _.get(claims, sails.config.custom.oidcNameAttribute),
},
username: sails.config.custom.oidcIgnoreUsername
? undefined
: {
attribute: sails.config.custom.oidcUsernameAttribute,
value: _.get(claims, sails.config.custom.oidcUsernameAttribute),
},
roles: sails.config.custom.oidcIgnoreRoles
? undefined
: {
attribute: sails.config.custom.oidcRolesAttribute,
value: _.get(claims, sails.config.custom.oidcRolesAttribute),
},
};
logs.push('📋 Mapping result:', JSON.stringify(mappings, null, 2), '');
if (!mappings.email.value) {
logs.push('❌ Email not resolved.');
logs.push('💡 Hint: Check email attribute mapping.', '');
}
if (!mappings.name.value) {
logs.push('❌ Name not resolved.');
logs.push('💡 Hint: Check name attribute mapping.', '');
}
if (!sails.config.custom.oidcIgnoreUsername) {
if (!mappings.username.value) {
logs.push('⚠️ Username not resolved.');
logs.push('💡 Hint: Check username attribute mapping.', '');
}
}
if (!sails.config.custom.oidcIgnoreRoles) {
if (!Array.isArray(mappings.roles.value) || mappings.roles.value.length === 0) {
logs.push('⚠️ Roles not resolved or empty.');
logs.push('💡 Hint: Check roles attribute mapping or IdP role configuration.', '');
} else {
logs.push('🎭 Resolving user role from OIDC roles...');
// Use a Set here to avoid quadratic time complexity
const claimsRolesSet = new Set(mappings.roles.value);
const foundRole = [User.Roles.ADMIN, User.Roles.PROJECT_OWNER, User.Roles.BOARD_USER].find(
(roleItem) => {
const configRoles = sails.config.custom[`oidc${_.upperFirst(roleItem)}Roles`];
if (configRoles.includes('*')) {
return true;
}
return configRoles.some((configRole) => claimsRolesSet.has(configRole));
},
);
if (foundRole) {
logs.push(`✅ Matched user role → ${_.lowerCase(foundRole)}`, '');
} else {
logs.push('⚠️ No user role matched configured OIDC roles.');
logs.push('💡 Hint: Check role matching settings.', '');
}
}
}
if (mappings.email.value && mappings.name.value) {
logs.push('🎉 OIDC debug completed successfully.');
} else {
logs.push('🛑 OIDC debug detected missing required attributes.');
}
return {
item: null,
included: {
logs,
},
};
},
};
@@ -0,0 +1,51 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
/**
* @swagger
* /access-tokens/me:
* delete:
* summary: User logout
* description: Logs out the current user by deleting the session and access token. Clears HTTP-only cookies if present.
* tags:
* - Access Tokens
* operationId: deleteAccessToken
* responses:
* 200:
* description: Logout successful
* content:
* application/json:
* schema:
* type: object
* required:
* - item
* properties:
* item:
* type: string
* description: Revoked access token
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ4...
* 401:
* $ref: '#/components/responses/Unauthorized'
* security:
* - bearerAuth: []
*/
module.exports = {
async fn() {
const { currentSession } = this.req;
await Session.qm.deleteOneById(currentSession.id);
sails.sockets.leaveAll(`@accessToken:${currentSession.accessToken}`);
if (currentSession.httpOnlyToken && !this.req.isSocket) {
sails.helpers.utils.clearHttpOnlyTokenCookie(this.res);
}
return {
item: currentSession.accessToken,
};
},
};
@@ -0,0 +1,271 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
/**
* @swagger
* /access-tokens/exchange-with-oidc:
* post:
* summary: Exchange OIDC code for access token
* description: Exchanges an OIDC authorization code for an access token. Creates a user if they do not exist.
* tags:
* - Access Tokens
* operationId: exchangeForAccessTokenWithOidc
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - nonce
* properties:
* code:
* type: string
* maxLength: 2048
* description: Authorization code from OIDC provider
* example: abc123def456ghi789
* nonce:
* type: string
* maxLength: 1024
* description: Nonce value for OIDC security
* example: random-nonce-123456
* withHttpOnlyToken:
* type: boolean
* description: Whether to include HTTP-only authentication cookie
* example: true
* responses:
* 200:
* description: OIDC exchange successful
* content:
* application/json:
* schema:
* type: object
* required:
* - item
* properties:
* item:
* type: string
* description: Access token for API authentication
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ4...
* headers:
* Set-Cookie:
* description: HTTP-only authentication cookie (if `withHttpOnlyToken` is true)
* schema:
* type: string
* example: httpOnlyToken=29aa3e38-8d24-4029-9743-9cbcf0a0dd5c; HttpOnly; Secure; SameSite=Strict
* 400:
* $ref: '#/components/responses/ValidationError'
* 401:
* description: OIDC authentication error
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_UNAUTHORIZED
* message:
* type: string
* enum:
* - Invalid code or nonce
* - Invalid userinfo configuration
* description: Specific error message
* example: Invalid code or nonce
* 403:
* description: Authentication restriction
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_FORBIDDEN
* message:
* type: string
* enum:
* - Terms acceptance required
* - Admin login required to initialize instance
* description: Specific error message
* example: Terms acceptance required
* 409:
* description: Conflict error
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_CONFLICT
* message:
* type: string
* enum:
* - Email already in use
* - Username already in use
* - Active users limit reached
* description: Specific error message
* example: Email already in use
* 422:
* description: Missing required values
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_UNPROCESSABLE_ENTITY
* message:
* type: string
* description: Error message
* example: Unable to retrieve required values (email, name)
* 500:
* description: OIDC configuration error
* content:
* application/json:
* schema:
* type: object
* required:
* - code
* - message
* properties:
* code:
* type: string
* description: Error code
* example: E_INTERNAL_SERVER_ERROR
* message:
* type: string
* description: Error message
* example: Invalid OIDC configuration
* security: []
*/
const { getRemoteAddress } = require('../../../utils/remote-address');
const Errors = {
INVALID_OIDC_CONFIGURATION: {
invalidOidcConfiguration: 'Invalid OIDC configuration',
},
INVALID_CODE_OR_NONCE: {
invalidCodeOrNonce: 'Invalid code or nonce',
},
INVALID_USERINFO_CONFIGURATION: {
invalidUserinfoConfiguration: 'Invalid userinfo configuration',
},
TERMS_ACCEPTANCE_REQUIRED: {
termsAcceptanceRequired: 'Terms acceptance required',
},
EMAIL_ALREADY_IN_USE: {
emailAlreadyInUse: 'Email already in use',
},
USERNAME_ALREADY_IN_USE: {
usernameAlreadyInUse: 'Username already in use',
},
ACTIVE_USERS_LIMIT_REACHED: {
activeUsersLimitReached: 'Active users limit reached',
},
MISSING_VALUES: {
missingValues: 'Unable to retrieve required values (email, name)',
},
};
module.exports = {
inputs: {
code: {
type: 'string',
maxLength: 2048,
required: true,
},
nonce: {
type: 'string',
maxLength: 1024,
required: true,
},
withHttpOnlyToken: {
type: 'boolean',
},
},
exits: {
invalidOidcConfiguration: {
responseType: 'serverError',
},
invalidCodeOrNonce: {
responseType: 'unauthorized',
},
invalidUserinfoConfiguration: {
responseType: 'unauthorized',
},
termsAcceptanceRequired: {
responseType: 'forbidden',
},
adminLoginRequiredToInitializeInstance: {
responseType: 'forbidden',
},
emailAlreadyInUse: {
responseType: 'conflict',
},
usernameAlreadyInUse: {
responseType: 'conflict',
},
activeUsersLimitReached: {
responseType: 'conflict',
},
missingValues: {
responseType: 'unprocessableEntity',
},
},
async fn(inputs) {
const remoteAddress = getRemoteAddress(this.req);
const user = await sails.helpers.users
.getOrCreateOneWithOidc(inputs.code, inputs.nonce)
.intercept('invalidOidcConfiguration', () => Errors.INVALID_OIDC_CONFIGURATION)
.intercept('invalidCodeOrNonce', () => {
sails.log.warn(`Invalid code or nonce! (IP: ${remoteAddress})`);
return Errors.INVALID_CODE_OR_NONCE;
})
.intercept('invalidUserinfoConfiguration', () => Errors.INVALID_USERINFO_CONFIGURATION)
.intercept('emailAlreadyInUse', () => Errors.EMAIL_ALREADY_IN_USE)
.intercept('usernameAlreadyInUse', () => Errors.USERNAME_ALREADY_IN_USE)
.intercept('activeLimitReached', () => Errors.ACTIVE_USERS_LIMIT_REACHED)
.intercept('missingValues', () => Errors.MISSING_VALUES);
return sails.helpers.accessTokens.handleSteps
.with({
user,
remoteAddress,
request: this.req,
response: this.res,
withHttpOnlyToken: inputs.withHttpOnlyToken,
})
.intercept('adminLoginRequiredToInitializeInstance', (error) => ({
adminLoginRequiredToInitializeInstance: error.raw,
}))
.intercept('termsAcceptanceRequired', (error) => ({
termsAcceptanceRequired: error.raw,
}));
},
};
@@ -0,0 +1,92 @@
/*!
* Copyright (c) 2024 PLANKA Software GmbH
* Licensed under the Fair Use License: https://github.com/plankanban/planka/blob/master/LICENSE.md
*/
/**
* @swagger
* /access-tokens/revoke-pending-token:
* post:
* summary: Revoke pending token
* description: Revokes a pending authentication token and cancels the authentication flow.
* tags:
* - Access Tokens
* operationId: revokePendingToken
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - pendingToken
* properties:
* pendingToken:
* type: string
* maxLength: 1024
* description: Pending token to revoke
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ4...
* responses:
* 200:
* description: Pending token revoked successfully
* content:
* application/json:
* schema:
* type: object
* properties:
* item:
* type: object
* nullable: true
* description: No data returned
* example: null
* 400:
* $ref: '#/components/responses/ValidationError'
* 404:
* $ref: '#/components/responses/NotFound'
* security: []
*/
const Errors = {
PENDING_TOKEN_NOT_FOUND: {
pendingTokenNotFound: 'Pending token not found',
},
};
module.exports = {
inputs: {
pendingToken: {
type: 'string',
maxLength: 1024,
required: true,
},
},
exits: {
pendingTokenNotFound: {
responseType: 'notFound',
},
},
async fn(inputs) {
const { httpOnlyToken } = this.req.cookies;
let session = await Session.qm.getOneUndeletedByPendingToken(inputs.pendingToken);
if (!session) {
throw Errors.PENDING_TOKEN_NOT_FOUND;
}
if (session.httpOnlyToken && httpOnlyToken !== session.httpOnlyToken) {
throw Errors.PENDING_TOKEN_NOT_FOUND; // Forbidden
}
session = await Session.qm.deleteOneById(session.id);
if (session.httpOnlyToken && !this.req.isSocket) {
sails.helpers.utils.clearHttpOnlyTokenCookie(this.res);
}
return {
item: null,
};
},
};