Skip to content

Commit

Permalink
Merge pull request #863 from NoodleOfDeath/dev
Browse files Browse the repository at this point in the history
~api
  • Loading branch information
NoodleOfDeath authored Jan 28, 2024
2 parents 81735f8 + c2ba91c commit 9eb1d53
Show file tree
Hide file tree
Showing 14 changed files with 167 additions and 108 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ export class AccountController extends BaseControllerWithPersistentStorageAccess
if (!token.user) {
throw new AuthError('UNKNOWN_ALIAS');
}
await token.user.syncProfile(); // get profile
await token.user.syncProfile(req); // get profile
return {
profile: token.user.toJSON().profile ?? {},
token: token.wrapped,
Expand All @@ -314,7 +314,7 @@ export class AccountController extends BaseControllerWithPersistentStorageAccess
if (!user) {
throw new AuthError('UNKNOWN_ALIAS');
}
await user.syncProfile(); // get profile
await user.syncProfile(req); // get profile
if (token) {
// account is anonymous, return JWT
return {
Expand Down Expand Up @@ -376,7 +376,7 @@ export class AccountController extends BaseControllerWithPersistentStorageAccess
}
}
// user is authenticated, generate JWT else {
await user.syncProfile(); // get profile
await user.syncProfile(req); // get profile
const userData = user.toJSON();
const token = await JWT.as(body.requestedRole ?? 'standard', userData.id);
await user.createCredential('jwt', token);
Expand Down Expand Up @@ -414,7 +414,7 @@ export class AccountController extends BaseControllerWithPersistentStorageAccess
@Body() body: RegisterAliasRequest
): Promise<RegistrationResponse> {
const user = await User.from(body, req.body);
await user.syncProfile();
await user.syncProfile(req);
if (user.toJSON().profile?.linkedThirdPartyAccounts?.includes(body.otherAlias.thirdParty.name)) {
throw new AuthError('DUPLICATE_USER');
}
Expand Down
18 changes: 8 additions & 10 deletions src/server/src/api/v1/controllers/category/CategoryController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ import {
Tags,
} from 'tsoa';

import {
BaseController,
BulkResponse,
InteractionRequest,
} from '../';
import { BaseController, BulkResponse } from '../';
import { SupportedLocale } from '../../../../core/locales';
import {
AuthError,
Expand All @@ -27,6 +23,7 @@ import {
import {
Category,
CategoryInteraction,
InteractionCreationAttributes,
InteractionType,
PublicCategoryAttributes,
} from '../../schema';
Expand Down Expand Up @@ -58,14 +55,15 @@ export class CategoryController extends BaseController {
@Request() req: ExpressRequest,
@Path() targetId: number,
@Path() type: InteractionType,
@Body() body: InteractionRequest
@Body() body: InteractionCreationAttributes,
): Promise<PublicCategoryAttributes> {
const user = req.jwt?.user;
const {
content, metadata, remoteAddr,
} = body;
const interaction = await CategoryInteraction.create({
content, metadata, remoteAddr, targetId, type, userId: user?.id,
...body,
remoteAddr: req.ip,
targetId,
type,
userId: user?.id,
});
if (!interaction) {
throw new InternalError('Failed to create interaction');
Expand Down
14 changes: 8 additions & 6 deletions src/server/src/api/v1/controllers/event/EventController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
Tags,
} from 'tsoa';

import { BulkResponse, InteractionRequest } from '../';
import { BulkResponse } from '../';
import {
AuthError,
Request as ExpressRequest,
Expand All @@ -21,6 +21,7 @@ import {
import {
Event,
EventInteraction,
InteractionCreationAttributes,
InteractionType,
PublicEventAttributes,
} from '../../schema';
Expand Down Expand Up @@ -50,14 +51,15 @@ export class EventController {
@Request() req: ExpressRequest,
@Path() targetId: number,
@Path() type: InteractionType,
@Body() body: InteractionRequest
@Body() body: InteractionCreationAttributes
): Promise<PublicEventAttributes> {
const user = req.jwt?.user;
const {
content, metadata, remoteAddr,
} = body;
const interaction = await EventInteraction.create({
content, metadata, remoteAddr, targetId, type, userId: user?.id,
...body,
remoteAddr: req.ip,
targetId,
type,
userId: user?.id,
});
if (!interaction) {
throw new InternalError('Failed to create interaction');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class ProfileController extends BaseControllerWithPersistentStorageAccess
@Request() req: ExpressRequest
): Promise<ProfileResponse> {
const user = req.jwt.user;
await user.syncProfile();
await user.syncProfile(req);
const userData = user.toJSON();
return { profile: userData.profile };
}
Expand Down
18 changes: 8 additions & 10 deletions src/server/src/api/v1/controllers/publisher/PublisherController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,15 @@ import {
Tags,
} from 'tsoa';

import {
BaseController,
BulkResponse,
InteractionRequest,
} from '..';
import { BaseController, BulkResponse } from '..';
import { SupportedLocale } from '../../../../core/locales';
import {
AuthError,
Request as ExpressRequest,
InternalError,
} from '../../middleware';
import {
InteractionCreationAttributes,
InteractionType,
PublicPublisherAttributes,
Publisher,
Expand Down Expand Up @@ -57,14 +54,15 @@ export class PublisherController extends BaseController {
@Request() req: ExpressRequest,
@Path() targetId: number,
@Path() type: InteractionType,
@Body() body: InteractionRequest
@Body() body: InteractionCreationAttributes,
): Promise<PublicPublisherAttributes> {
const user = req.jwt?.user;
const {
content, metadata, remoteAddr,
} = body;
const interaction = await PublisherInteraction.create({
content, metadata, remoteAddr, targetId, type, userId: user?.id,
...body,
remoteAddr: req.ip,
targetId,
type,
userId: user?.id,
});
if (!interaction) {
throw new InternalError('Failed to create interaction');
Expand Down
11 changes: 4 additions & 7 deletions src/server/src/api/v1/controllers/summary/SummaryController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
BulkMetadataResponse,
BulkResponse,
DestroyResponse,
InteractionRequest,
} from '../';
import { BaseControllerWithPersistentStorageAccess } from '../';
import { SupportedLocale } from '../../../../core/locales';
Expand All @@ -30,6 +29,7 @@ import {
InternalError,
} from '../../middleware';
import {
InteractionCreationAttributes,
InteractionType,
PublicRecapAttributes,
PublicSummaryAttributes,
Expand Down Expand Up @@ -132,14 +132,11 @@ export class SummaryController extends BaseControllerWithPersistentStorageAccess
@Request() req: ExpressRequest,
@Path() targetId: number,
@Path() type: InteractionType,
@Body() body: InteractionRequest
@Body() body: InteractionCreationAttributes
): Promise<PublicSummaryAttributes> {
const user = req.jwt?.user;
console.log(user);
const { content, metadata } = body;
const interaction = await SummaryInteraction.create({
content,
metadata,
...body,
remoteAddr: req.ip,
targetId,
type,
Expand All @@ -152,7 +149,7 @@ export class SummaryController extends BaseControllerWithPersistentStorageAccess
await new MailService().sendMail({
from: '[email protected]',
subject: 'Feedback',
text: [content, JSON.stringify(metadata)].join('\n\n'),
text: [body.content, JSON.stringify(body.metadata)].join('\n\n'),
to: '[email protected]',
});
}
Expand Down
27 changes: 0 additions & 27 deletions src/server/src/api/v1/controllers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,30 +50,3 @@ export type LocalizeRequest = JobRequest & {
export type TtsRequest = JobRequest & {
voice?: string;
};

// interactions

export type InteractionRequest = {
userId?: number;
remoteAddr?: string;
content?: string;
metadata?: Record<string, unknown>;
};

export type InteractionUserVote = 'down' | 'up';

// uh this type exists? forcing rebuild
export type InteractionResponse = {
bookmark: number;
userBookmarked?: boolean;
favorite: number;
userFavorited?: boolean;
comment: number;
downvote: number;
listen: number;
read: number;
share: number;
upvote: number;
uservote?: InteractionUserVote;
view: number;
};
1 change: 0 additions & 1 deletion src/server/src/api/v1/middleware/AuthMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { AuthError, internalErrorHandler } from './internal-errors';
import { RequestHandler } from './types';
import { JWT } from '../controllers/types';

type AuthMiddlewareOptions = {
scope?: string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ export const preprocessHeadersMiddleware: RequestHandler = async (req, res, next
try {
delete req.body.userId;
delete req.query.userId;
req.ip = req.get('x-forwarded-from') || req.ip;
const auth = req.get('authorization') || '';
const [type, token] = auth.split(' ');
if (type === 'Bearer') {
const jwt = await JWT.from(token);
req.jwt = jwt;
req.body.userId = jwt.userId;
}
const version = req.get('x-version');
req.version = version;
next();
} catch (e) {
internalErrorHandler(res, e);
Expand Down
1 change: 1 addition & 0 deletions src/server/src/api/v1/middleware/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { JWT } from '../controllers/types';

export type Request = ExpressRequest & {
jwt?: JWT;
version?: string;
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,21 +159,21 @@ export class Achievement<
const data = await UserMetadata.findAll({
where: { key: 'bookmarkedSummaries' }
});
const users = data.filter((d) => (JSON.parse(d) as number[]).length >= 3).map((d) => d.userId);
const users = data.filter((d) => Object.values(d.value).length >= 3).map((d) => d.userId);
return await User.findAll({ where : { id: users } });
} catch (e) {
console.error(e);
}
},
getProgress: async (user) => {
try {
const data = await UserMetadata.findAll({
const data = await UserMetadata.findOne({
where: {
key: 'bookmarkedSummaries',
userId: user.id,
}
});
const count = (JSON.parse(data?.value ?? '[]') as number[]).length;
const count = (Object.values(data?.value ?? [])).length;
return count / 3;
} catch (e) {
return 0
Expand All @@ -190,21 +190,21 @@ export class Achievement<
const data = await UserMetadata.findAll({
where: { key: 'bookmarkedSummaries' }
});
const users = data.filter((d) => (JSON.parse(d) as number[]).length >= 10).map((d) => d.userId);
const users = data.filter((d) => Object.values(d.value).length >= 10).map((d) => d.userId);
return await User.findAll({ where : { id: users } });
} catch (e) {
console.error(e);
}
},
getProgress: async (user) => {
try {
const data = await UserMetadata.findAll({
const data = await UserMetadata.findOne({
where: {
key: 'bookmarkedSummaries',
userId: user.id,
}
});
const count = (JSON.parse(data?.value ?? '[]') as number[]).length;
const count = (Object.values(data?.value ?? [])).length;
return count / 10;
} catch (e) {
return 0
Expand All @@ -221,21 +221,21 @@ export class Achievement<
const data = await UserMetadata.findAll({
where: { key: 'bookmarkedSummaries' }
});
const users = data.filter((d) => (JSON.parse(d) as number[]).length >= 30).map((d) => d.userId);
const users = data.filter((d) => Object.values(d.value).length >= 30).map((d) => d.userId);
return await User.findAll({ where : { id: users } });
} catch (e) {
console.error(e);
}
},
getProgress: async (user) => {
try {
const data = await UserMetadata.findAll({
const data = await UserMetadata.findOne({
where: {
key: 'bookmarkedSummaries',
userId: user.id,
}
});
const count = (JSON.parse(data?.value ?? '[]') as number[]).length;
const count = Object.values(data?.value ?? []).length;
return count / 30;
} catch (e) {
return 0
Expand All @@ -252,21 +252,21 @@ export class Achievement<
const data = await UserMetadata.findAll({
where: { key: 'bookmarkedSummaries' }
});
const users = data.filter((d) => (JSON.parse(d) as number[]).length >= 100).map((d) => d.userId);
const users = data.filter((d) => Object.values(d.value).length >= 100).map((d) => d.userId);
return await User.findAll({ where : { id: users } });
} catch (e) {
console.error(e);
}
},
getProgress: async (user) => {
try {
const data = await UserMetadata.findAll({
const data = await UserMetadata.findOne({
where: {
key: 'bookmarkedSummaries',
userId: user.id,
}
});
const count = (JSON.parse(data?.value ?? '[]') as number[]).length;
const count = Object.values(data?.value ?? []).length;
return count / 100;
} catch (e) {
return 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,17 @@ export abstract class Interaction<
type: DataType.STRING,
})
declare type: InteractionType;

@Column({
defaultValue: false,
type: DataType.BOOLEAN,
})
declare revert: boolean;

@Column({ type: DataType.TEXT })
declare content?: string;

@Column({ type: DataType.JSON })
declare metadata?: Record<string, unknown>;

}
Loading

0 comments on commit 9eb1d53

Please sign in to comment.