Files
habitica/website/server/middlewares/auth.js
negue 2535fd7095 Combined Message Pages/Redesign (#15310)
* split component prepare new views / states

* extract empty and disabled state as components

* fix empty state mail icon

* first logic switching between modes, move page to /private-messages/index.vue

* extract autoCompleteHelper.js

* style header + start new message input

* style plus button + focus input

* state logic, types for sanity

* WIP PM new Message started

* add /members/username test

* first design changes to messageCard

* delete private message or chat - based on the mode

* copy as todo

* mention links to modal

* report chat or private message

* WIP likeButton

* likeButton styling

* hide like on private message cards

* fix unit test

* replace copy as todo - to just a copy to clipboard

* style changes

* menu position + like button width

* dropdown items background + like font

* fix like button padding

* move api endpoints and tests around to group inbox methods  + like for inbox private messages

* restyle system messages

* Dropdown Radius and Padding

* WIP system messages

* fix lint

* copy delta commit of allowing liking own private messages

* enable liking private messages

* fix menu non hovered item icon color

* fix import path

* ignore background on system messages

* requested changes + migration

* update migration to update the unique id to some messages and delete the duplicates

* migration based on users pagination

* fix(migration): use Promise.all

* change to bulkWrites per User, and all messages in one run (of a user)

* check for array

* use rest operator ...

* skip sorting to get the users

* remove migration, disable like for private messages without uniqueMessageId

* lean+bulkWrite for likes, add time checks for like and auth for further debugging

* add a limit 2 get the messages by uniqueId

* Adding a simple server start script

* remove pinned nodemon dep

* fix inbox controller/tests

* fix / requested style changes

* fix empty state padding /

* hide avatar weapons on messages - fix avatar spacing on messages

* Hourglass Simplification (#15323)

* begin removing obsolete tests

* begin refactoring

* update cron tests

* cleanup

* finish basic implementation of new logic

* add more subscription tests

* subscription test improvements

* return nextHourglassDate again

* fix gem limit

* fix(test): short circuit this.

* fix(admin): correct logic and style for shrimple subs

* WIP(frontend): draft of main subs page view

* fix hourglass count

* Fix hourglass logic for upgrades

* fix admin panel display

* WIP(subs): extant Stripe state

* fix admin panel strings

* fix missing transaction type

* add new field for cumulative subscription count

* show date for hourglass bonus if it was received

* fix test

* feat(subscription): max Gems progress readout

* fix(css): correct and refactor heights and selection states

* fix(subs): correct border-radius and redirect

* fix(stripe): correct redirect after success

* Admin panel display fixes

* don’t give additional HG for new sub if they already got one this month

* fix issue with promo hourglasses

* fix(subscription): update layout when gifting

* fix(subscriptions): more gift layout revisions

* fix(subscriptions): minor visual updates

* fix(subs): pass autoRenews through Stripe

* fix(subs): gifts DON't renew

* fix(lint): unnecessary ternary

* fix(lint): do negate object ig

* fix(subs): try again on gifts

* fix(subs): unhovery and un-12-monthy

* fix bug with incorrectly giving HG bonus

* remove only

* fix test

* fix test

* fix(subs): also redirect to subs after gift sub

* fix(subs): fix typeError

* fix(g1g1): don't try to find Gems promo during bogo

---------

Co-authored-by: Phillip Thelen <phillip@habitica.com>
Co-authored-by: Kalista Payne <sabe@habitica.com>

* chore(sprites): update subproject

* fix(layout): tighten cancellation note

* fix(subs): Google wording and HG escape

* chore(testing): fake g1g1 dates

* fix(subs): don't hide HG preview entirely

* fix(subs): center next hourglass message

* working validatedTextInput.vue within start-new-conversation-input-header.vue 🎉

* fix(git): remove changes from old develop

* Revert "fix(git): remove changes from old develop"

This reverts commit 0e30f7df00.

* fix(git): no actually just this file i guesss

* adding an empty loading state, hiding

* fought the avatar arch nemesis again

* fix chatMessages (party chat) message spacing

* move disabled text back to above the input area - re-enable input area

* show disabled private messages top panel

* fix font color

* fixing uiStates - removing disabled - moving the own user check to the last

* fix(lint): add missing prop defaults

* fix(lint): object default should be fn

* fix(chat): correct grammar in error

---------

Co-authored-by: SabreCat <sabe@habitica.com>
Co-authored-by: Kalista Payne <sabrecat@gmail.com>
Co-authored-by: Phillip Thelen <phillip@habitica.com>
2025-01-16 16:52:24 -06:00

143 lines
4.8 KiB
JavaScript

import moment from 'moment';
import nconf from 'nconf';
import url from 'url';
import {
NotAuthorized,
} from '../libs/errors';
import {
model as User,
} from '../models/user';
import gcpStackdriverTracer from '../libs/gcpTraceAgent';
import common from '../../common';
import { getLanguageFromUser } from '../libs/language';
import { logTime } from '../libs/logger';
const OFFICIAL_PLATFORMS = ['habitica-web', 'habitica-ios', 'habitica-android'];
const COMMUNITY_MANAGER_EMAIL = nconf.get('EMAILS_COMMUNITY_MANAGER_EMAIL');
const USER_FIELDS_ALWAYS_LOADED = ['_id', '_v', 'notifications', 'preferences', 'auth', 'flags', 'permissions'];
function getUserFields (options, req) {
// A list of user fields that aren't needed for the route and are not loaded from the db.
// Must be an array
if (options.userFieldsToExclude) {
return options.userFieldsToExclude
.filter(field => !USER_FIELDS_ALWAYS_LOADED
.find(fieldToInclude => field.startsWith(fieldToInclude)))
.map(field => `-${field}`) // -${field} means exclude ${field} in mongodb
.join(' ');
}
if (options.userFieldsToInclude) {
return options.userFieldsToInclude.concat(USER_FIELDS_ALWAYS_LOADED).join(' ');
}
// Allows GET requests to /user to specify a list
// of user fields to return instead of the entire doc
const urlPath = url.parse(req.url).pathname;
const { userFields } = req.query;
if (!userFields || urlPath !== '/user') return '';
let userFieldOptions = userFields.split(',');
if (userFieldOptions.length === 0) return '';
userFieldOptions = userFieldOptions.filter(field => USER_FIELDS_ALWAYS_LOADED.indexOf(field.split('.')[0]) === -1);
return userFieldOptions.concat(USER_FIELDS_ALWAYS_LOADED).join(' ');
}
// Make sure stackdriver traces are storing the user id
function stackdriverTraceUserId (userId) {
if (gcpStackdriverTracer) {
gcpStackdriverTracer.getCurrentRootSpan().addLabel('userId', userId);
}
}
// Strins won't be translated here because getUserLanguage has not run yet
// Authenticate a request through the x-api-user and x-api key header
// If optional is true, don't error on missing authentication
export function authWithHeaders (options = {}) {
return function authWithHeadersHandler (req, res, next) {
const authHandlerTime = logTime(req.url, 'authWithHeadersHandler');
const userId = req.header('x-api-user');
const apiToken = req.header('x-api-key');
const client = req.header('x-client');
const optional = options.optional || false;
if (!userId || !apiToken) {
if (optional) return next();
return next(new NotAuthorized(res.t('missingAuthHeaders')));
}
const userQuery = { _id: userId };
let fields = getUserFields(options, req);
// If the request didn't include the API Token, retrieve it for validation
if (fields && fields.indexOf('apiToken') === -1 && fields.indexOf('-') === -1) {
fields = `${fields} apiToken`;
}
const findPromise = fields ? User.findOne(userQuery).select(fields) : User.findOne(userQuery);
return findPromise
.exec()
.then(user => {
if (!user || apiToken !== user.apiToken) {
throw new NotAuthorized(res.t('invalidCredentials'));
}
if (user.auth.blocked) {
// We want the accountSuspended message to be translated but the language
// middleware hasn't run yet so we pick it manually
const language = getLanguageFromUser(user, req);
throw new NotAuthorized(common.i18n.t('accountSuspended', {
communityManagerEmail: COMMUNITY_MANAGER_EMAIL,
userId: user._id,
}, language));
}
res.locals.user = user;
req.session.userId = user._id;
stackdriverTraceUserId(user._id);
user.auth.timestamps.updated = new Date();
if (OFFICIAL_PLATFORMS.indexOf(client) === -1
&& (!user.flags.thirdPartyTools || moment().diff(user.flags.thirdPartyTools, 'days') > 0)
) {
User.updateOne(userQuery, { $set: { 'flags.thirdPartyTools': new Date() } }).exec();
}
authHandlerTime();
return next();
})
.catch(next);
};
}
// Authenticate a request through a valid session
export function authWithSession (req, res, next) {
const { userId } = req.session;
// Always allow authentication with headers
if (!userId) {
if (!req.header('x-api-user') || !req.header('x-api-key')) {
return next(new NotAuthorized(res.t('invalidCredentials')));
}
return authWithHeaders()(req, res, next);
}
return User.findOne({
_id: userId,
})
.exec()
.then(user => {
if (!user) throw new NotAuthorized(res.t('invalidCredentials'));
res.locals.user = user;
stackdriverTraceUserId(user._id);
user.auth.timestamps.updated = new Date();
return next();
})
.catch(next);
}