Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/api/env/.env.functional.test
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ FEE_ALLOWANCE_REFILL_THRESHOLD=500000
DEPLOYMENT_GRANT_DENOM=uakt
LOG_LEVEL=debug
BILLING_ENABLED=true
ANONYMOUS_USER_TOKEN_SECRET=ANONYMOUS_USER_TOKEN_SECRET
STRIPE_SECRET_KEY=STRIPE_SECRET_KEY
STRIPE_PRODUCT_ID=STRIPE_PRODUCT_ID
STRIPE_WEBHOOK_SECRET=STRIPE_WEBHOOK_SECRET
Expand Down
1 change: 0 additions & 1 deletion apps/api/env/.env.local.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ NETWORK=sandbox
DB_HOST_WITH_DEFAULT=${DB_HOST:-localhost}
CHAIN_INDEXER_POSTGRES_DB_URI=postgres://postgres:password@${DB_HOST_WITH_DEFAULT}:5432/console-akash-sandbox
POSTGRES_DB_URI=postgres://postgres:password@${DB_HOST_WITH_DEFAULT}:5432/console-users
ANONYMOUS_USER_TOKEN_SECRET=ANONYMOUS_USER_TOKEN_SECRET
MASTER_WALLET_MNEMONIC=MASTER_WALLET_MNEMONIC

AKASHLYTICS_CORS_WEBSITE_URLS="http://localhost:3000,http://localhost:3001"
Expand Down
1 change: 0 additions & 1 deletion apps/api/env/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
POSTGRES_DB_URI=
CHAIN_INDEXER_POSTGRES_DB_URI=
GITHUB_PAT=
ANONYMOUS_USER_TOKEN_SECRET=
HealthChecks_SyncAKTMarketData=
OLD_MASTER_WALLET_MNEMONIC=
FUNDING_WALLET_MNEMONIC=
Expand Down
1 change: 0 additions & 1 deletion apps/api/env/.env.unit.test
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ FEE_ALLOWANCE_REFILL_THRESHOLD=500000
DEPLOYMENT_GRANT_DENOM=uakt
LOG_LEVEL=debug
BILLING_ENABLED=true
ANONYMOUS_USER_TOKEN_SECRET=ANONYMOUS_USER_TOKEN_SECRET
STRIPE_SECRET_KEY=STRIPE_SECRET_KEY
STRIPE_PRODUCT_ID=STRIPE_PRODUCT_ID
STRIPE_WEBHOOK_SECRET=STRIPE_WEBHOOK_SECRET
Expand Down
1 change: 0 additions & 1 deletion apps/api/src/auth/config/env.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { z } from "zod";

export const envSchema = z.object({
ANONYMOUS_USER_TOKEN_SECRET: z.string(),
AUTH0_M2M_DOMAIN: z.string(),
AUTH0_M2M_CLIENT_ID: z.string(),
AUTH0_M2M_SECRET: z.string(),
Expand Down
28 changes: 3 additions & 25 deletions apps/api/src/auth/services/ability/ability.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,15 @@ import type { TemplateExecutor } from "lodash";
import template from "lodash/template";
import { singleton } from "tsyringe";

import { FeatureFlags, FeatureFlagValue } from "@src/core/services/feature-flags/feature-flags";
import { FeatureFlagsService } from "@src/core/services/feature-flags/feature-flags.service";
import type { UserOutput } from "@src/user/repositories";

type Role = "REGULAR_USER" | "REGULAR_ANONYMOUS_USER" | "REGULAR_PAYING_USER" | "SUPER_USER";
type Role = "REGULAR_USER" | "REGULAR_PAYING_USER" | "SUPER_USER";

@singleton()
export class AbilityService {
readonly EMPTY_ABILITY = createMongoAbility([]);

private readonly RULES: Record<Role, Array<RawRule & { enabledIf?: FeatureFlagValue }>> = {
REGULAR_ANONYMOUS_USER: [
{ action: ["read", "sign"], subject: "UserWallet", conditions: { userId: "${user.id}" } },
{ action: "create", subject: "UserWallet", conditions: { userId: "${user.id}" }, enabledIf: FeatureFlags.ANONYMOUS_FREE_TRIAL },
{ action: "read", subject: "User", conditions: { id: "${user.id}" } },
{ action: "verify-email", subject: "User", conditions: { email: "${user.email}" } },
{ action: "manage", subject: "DeploymentSetting", conditions: { userId: "${user.id}" } }
],
private readonly RULES: Record<Role, Array<RawRule>> = {
REGULAR_USER: [
{ action: ["create", "read", "sign"], subject: "UserWallet", conditions: { userId: "${user.id}" } },
{ action: "manage", subject: "WalletSetting", conditions: { userId: "${user.id}" } },
Expand Down Expand Up @@ -49,12 +40,6 @@ export class AbilityService {

private compiledRules?: Record<Role, TemplateExecutor>;

constructor(private readonly featureFlagsService: FeatureFlagsService) {
this.featureFlagsService.onChanged(() => {
this.compiledRules = undefined;
});
}

getAbilityFor(role: Role, user: UserOutput) {
const compiledRules = this.compileRules();
return this.toAbility(compiledRules[role]({ user }));
Expand All @@ -63,14 +48,7 @@ export class AbilityService {
private compileRules() {
this.compiledRules ??= (Object.keys(this.RULES) as Role[]).reduce(
(acc, role) => {
const rules = this.RULES[role].reduce<RawRule[]>((acc, { enabledIf, ...rule }) => {
if (!enabledIf || this.featureFlagsService.isEnabled(enabledIf)) {
acc.push(rule);
}
return acc;
}, []);

acc[role] = template(JSON.stringify(rules));
acc[role] = template(JSON.stringify(this.RULES[role]));
return acc;
},
{} as Record<Role, TemplateExecutor>
Expand Down
37 changes: 0 additions & 37 deletions apps/api/src/auth/services/auth-token/auth-token.service.ts

This file was deleted.

17 changes: 1 addition & 16 deletions apps/api/src/auth/services/auth.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { singleton } from "tsyringe";

import { AbilityService } from "@src/auth/services/ability/ability.service";
import { AuthService } from "@src/auth/services/auth.service";
import { AuthTokenService } from "@src/auth/services/auth-token/auth-token.service";
import { ExecutionContextService } from "@src/core/services/execution-context/execution-context.service";
import type { HonoInterceptor } from "@src/core/types/hono-interceptor.type";
import { UserOutput, UserRepository } from "@src/user/repositories";
Expand All @@ -30,7 +29,6 @@ export class AuthInterceptor implements HonoInterceptor {
private readonly abilityService: AbilityService,
private readonly userRepository: UserRepository,
private readonly authService: AuthService,
private readonly anonymousUserAuthService: AuthTokenService,
private readonly userAuthService: UserAuthTokenService,
private readonly apiKeyRepository: ApiKeyRepository,
private readonly apiKeyAuthService: ApiKeyAuthService,
Expand All @@ -41,15 +39,6 @@ export class AuthInterceptor implements HonoInterceptor {
return async (c: Context, next: Next) => {
const bearer = c.req.header("authorization");

const anonymousUserId = bearer && (await this.anonymousUserAuthService.getValidUserId(bearer));

if (anonymousUserId) {
const currentUser = await this.userRepository.findAnonymousById(anonymousUserId);
await this.auth(currentUser);
c.set("user", currentUser);
return await next();
}

const userId = bearer && (await this.userAuthService.getValidUserId(bearer, c.env));

if (userId) {
Expand Down Expand Up @@ -96,11 +85,7 @@ export class AuthInterceptor implements HonoInterceptor {
}

private getUserRole(user: UserOutput) {
if (user.userId) {
return user.trial === false ? "REGULAR_PAYING_USER" : "REGULAR_USER";
}

return "REGULAR_ANONYMOUS_USER";
return user.trial === false ? "REGULAR_PAYING_USER" : "REGULAR_USER";
}

private shouldMarkUserAsActive(userId: UserOutput["id"], now: Date): boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import { InjectTypeRegistry } from "@src/billing/providers/type-registry.provide
import { UserWalletOutput, UserWalletRepository } from "@src/billing/repositories";
import { TxManagerService } from "@src/billing/services/tx-manager/tx-manager.service";
import { DomainEventsService } from "@src/core/services/domain-events/domain-events.service";
import { FeatureFlags } from "@src/core/services/feature-flags/feature-flags";
import { FeatureFlagsService } from "@src/core/services/feature-flags/feature-flags.service";
import { UserOutput, UserRepository } from "@src/user/repositories";
import { BalancesService } from "../balances/balances.service";
import { ChainErrorService } from "../chain-error/chain-error.service";
Expand All @@ -31,7 +29,6 @@ export class ManagedSignerService {
private readonly authService: AuthService,
private readonly chainErrorService: ChainErrorService,
private readonly anonymousValidateService: TrialValidationService,
private readonly featureFlagsService: FeatureFlagsService,
private readonly txManagerService: TxManagerService,
private readonly domainEvents: DomainEventsService,
private readonly leaseHttpService: LeaseHttpService
Expand Down Expand Up @@ -87,7 +84,7 @@ export class ManagedSignerService {
async executeDecodedTxByUserWallet(
userWallet: UserWalletOutput,
messages: EncodeObject[],
walletOwner?: UserOutput
_walletOwner?: UserOutput
): Promise<{
code: number;
hash: string;
Expand All @@ -104,21 +101,8 @@ export class ManagedSignerService {

await this.anonymousValidateService.validateLeaseProvidersAuditors(messages, userWallet);

if (this.featureFlagsService.isEnabled(FeatureFlags.ANONYMOUS_FREE_TRIAL)) {
const user = walletOwner?.id === userWallet.userId ? walletOwner : await this.userRepository.findById(userWallet.userId!);
assert(user, 500, "User for wallet not found");
await Promise.all(
messages.map(message =>
Promise.all([
this.anonymousValidateService.validateLeaseProviders(message, userWallet, user),
this.anonymousValidateService.validateTrialLimit(message, userWallet)
])
)
);
}

const createLeaseMessage: { typeUrl: string; value: MsgCreateLease } | undefined = messages.find(message => message.typeUrl.endsWith(".MsgCreateLease"));
const hasCreateTrialLeaseMessage = userWallet.isTrialing && !!createLeaseMessage && !this.featureFlagsService.isEnabled(FeatureFlags.ANONYMOUS_FREE_TRIAL);
const hasCreateTrialLeaseMessage = userWallet.isTrialing && !!createLeaseMessage;
const hasLeases = hasCreateTrialLeaseMessage ? await this.leaseHttpService.hasLeases(userWallet.address!) : null;

const tx = await this.executeDerivedTx(userWallet.id, messages, userWallet.isOldWallet ?? false);
Expand Down
3 changes: 1 addition & 2 deletions apps/api/src/core/services/feature-flags/feature-flags.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
export const FeatureFlags = {
NOTIFICATIONS_ALERT_CREATE: "notifications_general_alerts_create",
NOTIFICATIONS_ALERT_UPDATE: "notifications_general_alerts_update",
ANONYMOUS_FREE_TRIAL: "anonymous_free_trial"
NOTIFICATIONS_ALERT_UPDATE: "notifications_general_alerts_update"
} as const;

export type FeatureFlagValue = (typeof FeatureFlags)[keyof typeof FeatureFlags];
32 changes: 2 additions & 30 deletions apps/api/src/user/controllers/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,18 @@ import assert from "http-assert";
import { singleton } from "tsyringe";

import { AuthService, Protected } from "@src/auth/services/auth.service";
import { AuthTokenService } from "@src/auth/services/auth-token/auth-token.service";
import { UserAuthTokenService } from "@src/auth/services/user-auth-token/user-auth-token.service";
import { ExecutionContextService } from "@src/core/services/execution-context/execution-context.service";
import { UserRepository } from "@src/user/repositories";
import type { GetUserParams } from "@src/user/routes/get-anonymous-user/get-anonymous-user.router";
import type { RegisterUserInput, RegisterUserResponse } from "@src/user/routes/register-user/register-user.router";
import { AnonymousUserResponseOutput, GetUserResponseOutput, UserSchema } from "@src/user/schemas/user.schema";
import { UserSchema } from "@src/user/schemas/user.schema";
import { UserService } from "@src/user/services/user/user.service";

@singleton()
export class UserController {
constructor(
private readonly userRepository: UserRepository,
private readonly authService: AuthService,
private readonly anonymousUserAuthService: AuthTokenService,
private readonly executionContextService: ExecutionContextService,
private readonly userService: UserService,
private readonly userAuthTokenService: UserAuthTokenService
Expand All @@ -27,35 +24,10 @@ export class UserController {
return this.executionContextService.get("HTTP_CONTEXT")!;
}

async create(): Promise<AnonymousUserResponseOutput> {
const user = await this.userRepository.create({
lastIp: this.httpContext.var.clientInfo?.ip,
lastUserAgent: this.httpContext.var.clientInfo?.userAgent,
lastFingerprint: this.httpContext.var.clientInfo?.fingerprint
});
return {
data: user,
token: this.anonymousUserAuthService.signTokenFor({ id: user.id })
};
}

@Protected([{ action: "read", subject: "User" }])
async getById({ id }: GetUserParams): Promise<{ data: UserSchema } | GetUserResponseOutput> {
const user = await this.userRepository.accessibleBy(this.authService.ability, "read").findById(id);

assert(user, 404);

return { data: user };
}

async registerUser(data: RegisterUserInput): Promise<RegisterUserResponse> {
const { req, env, var: httpVars } = this.httpContext;
const [userId, anonymousUserId] = await Promise.all([
this.userAuthTokenService.getValidUserId(req.header("authorization") || "", env),
this.anonymousUserAuthService.getValidUserId(req.header("x-anonymous-authorization") || "")
]);
const userId = await this.userAuthTokenService.getValidUserId(req.header("authorization") || "", env);
const user = await this.userService.registerUser({
anonymousUserId,
userId,
wantedUsername: data.wantedUsername,
email: data.email,
Expand Down
6 changes: 1 addition & 5 deletions apps/api/src/user/repositories/user/user.repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { and, eq, isNull, lt, SQL, sql } from "drizzle-orm";
import { and, eq, lt, SQL, sql } from "drizzle-orm";
import { PgUpdateSetSource } from "drizzle-orm/pg-core";
import { singleton } from "tsyringe";

Expand Down Expand Up @@ -39,10 +39,6 @@ export class UserRepository extends BaseRepository<ApiPgTables["Users"], UserInp
return this.findUserWithWallet(eq(this.table.userId, userId!));
}

async findAnonymousById(id: UserOutput["id"]) {
return await this.cursor.query.Users.findFirst({ where: this.whereAccessibleBy(and(eq(this.table.id, id), isNull(this.table.userId))) });
}

async markAsActive(
id: UserOutput["id"],
options: {
Expand Down

This file was deleted.

This file was deleted.

2 changes: 0 additions & 2 deletions apps/api/src/user/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
export * from "@src/user/routes/create-anonymous-user/create-anonymous-user.router";
export * from "@src/user/routes/get-anonymous-user/get-anonymous-user.router";
export * from "@src/user/routes/register-user/register-user.router";
export * from "@src/user/routes/get-current-user/get-current-user.router";
Loading