Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server): setup api for selfhost deployment #7569

Merged
merged 1 commit into from
Jul 23, 2024
Merged
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
7 changes: 3 additions & 4 deletions packages/backend/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ADD_ENABLED_FEATURES, ServerConfigModule } from './core/config';
import { DocModule } from './core/doc';
import { FeatureModule } from './core/features';
import { QuotaModule } from './core/quota';
import { CustomSetupModule } from './core/setup';
import { StorageModule } from './core/storage';
import { SyncModule } from './core/sync';
import { UserModule } from './core/user';
Expand Down Expand Up @@ -175,13 +176,11 @@ function buildAppModule() {
// self hosted server only
.useIf(
config => config.isSelfhosted,
CustomSetupModule,
ServeStaticModule.forRoot({
rootPath: join('/app', 'static'),
exclude: ['/admin*'],
})
)
.useIf(
config => config.isSelfhosted,
}),
ServeStaticModule.forRoot({
rootPath: join('/app', 'static', 'admin'),
serveRoot: '/admin',
Expand Down
42 changes: 7 additions & 35 deletions packages/backend/server/src/core/auth/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,7 @@ import { PrismaClient } from '@prisma/client';
import type { CookieOptions, Request, Response } from 'express';
import { assign, omit } from 'lodash-es';

import {
Config,
CryptoHelper,
EmailAlreadyUsed,
MailService,
WrongSignInCredentials,
WrongSignInMethod,
} from '../../fundamentals';
import { Config, EmailAlreadyUsed, MailService } from '../../fundamentals';
import { FeatureManagementService } from '../features/management';
import { QuotaService } from '../quota/service';
import { QuotaType } from '../quota/types';
Expand Down Expand Up @@ -74,20 +67,19 @@ export class AuthService implements OnApplicationBootstrap {
private readonly mailer: MailService,
private readonly feature: FeatureManagementService,
private readonly quota: QuotaService,
private readonly user: UserService,
private readonly crypto: CryptoHelper
private readonly user: UserService
) {}

async onApplicationBootstrap() {
if (this.config.node.dev) {
try {
const [email, name, pwd] = ['dev@affine.pro', 'Dev User', 'dev'];
const [email, name, password] = ['dev@affine.pro', 'Dev User', 'dev'];
let devUser = await this.user.findUserByEmail(email);
if (!devUser) {
devUser = await this.user.createUser({
email,
name,
password: await this.crypto.encryptPassword(pwd),
password,
});
}
await this.quota.switchUserQuota(devUser.id, QuotaType.ProPlanV1);
Expand All @@ -114,36 +106,17 @@ export class AuthService implements OnApplicationBootstrap {
throw new EmailAlreadyUsed();
}

const hashedPassword = await this.crypto.encryptPassword(password);

return this.user
.createUser({
name,
email,
password: hashedPassword,
password,
})
.then(sessionUser);
}

async signIn(email: string, password: string) {
const user = await this.user.findUserWithHashedPasswordByEmail(email);

if (!user) {
throw new WrongSignInCredentials();
}

if (!user.password) {
throw new WrongSignInMethod();
}

const passwordMatches = await this.crypto.verifyPassword(
password,
user.password
);

if (!passwordMatches) {
throw new WrongSignInCredentials();
}
const user = await this.user.signIn(email, password);

return sessionUser(user);
}
Expand Down Expand Up @@ -382,8 +355,7 @@ export class AuthService implements OnApplicationBootstrap {
id: string,
newPassword: string
): Promise<Omit<User, 'password'>> {
const hashedPassword = await this.crypto.encryptPassword(newPassword);
return this.user.updateUser(id, { password: hashedPassword });
return this.user.updateUser(id, { password: newPassword });
}

async changeEmail(
Expand Down
12 changes: 10 additions & 2 deletions packages/backend/server/src/core/config/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
ResolveField,
Resolver,
} from '@nestjs/graphql';
import { RuntimeConfig, RuntimeConfigType } from '@prisma/client';
import { PrismaClient, RuntimeConfig, RuntimeConfigType } from '@prisma/client';
import { GraphQLJSON, GraphQLJSONObject } from 'graphql-scalars';

import { Config, DeploymentType, URLHelper } from '../../fundamentals';
Expand Down Expand Up @@ -115,7 +115,8 @@ export class ServerFlagsType implements ServerFlags {
export class ServerConfigResolver {
constructor(
private readonly config: Config,
private readonly url: URLHelper
private readonly url: URLHelper,
private readonly db: PrismaClient
) {}

@Public()
Expand Down Expand Up @@ -165,6 +166,13 @@ export class ServerConfigResolver {
return flags;
}, {} as ServerFlagsType);
}

@ResolveField(() => Boolean, {
description: 'whether server has been initialized',
})
async initialized() {
return (await this.db.user.count()) > 0;
}
}

@Resolver(() => ServerRuntimeConfigType)
Expand Down
7 changes: 6 additions & 1 deletion packages/backend/server/src/core/features/management.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common';

import { Config } from '../../fundamentals';
import { Config, type EventPayload, OnEvent } from '../../fundamentals';
import { UserService } from '../user/service';
import { FeatureService } from './service';
import { FeatureType } from './types';
Expand Down Expand Up @@ -167,4 +167,9 @@ export class FeatureManagementService {
async listFeatureWorkspaces(feature: FeatureType) {
return this.feature.listFeatureWorkspaces(feature);
}

@OnEvent('user.admin.created')
async onAdminUserCreated({ id }: EventPayload<'user.admin.created'>) {
await this.addAdmin(id);
}
}
3 changes: 2 additions & 1 deletion packages/backend/server/src/core/features/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export class FeatureManagementResolver {
if (user) {
return this.feature.addEarlyAccess(user.id, type);
} else {
const user = await this.users.createAnonymousUser(email, {
const user = await this.users.createUser({
email,
registered: false,
});
return this.feature.addEarlyAccess(user.id, type);
Expand Down
66 changes: 66 additions & 0 deletions packages/backend/server/src/core/setup/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Body, Controller, Post, Req, Res } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
import type { Request, Response } from 'express';

import {
ActionForbidden,
EventEmitter,
InternalServerError,
MutexService,
PasswordRequired,
} from '../../fundamentals';
import { AuthService, Public } from '../auth';
import { UserService } from '../user/service';

interface CreateUserInput {
email: string;
password: string;
}

@Controller('/api/setup')
export class CustomSetupController {
constructor(
private readonly db: PrismaClient,
private readonly user: UserService,
private readonly auth: AuthService,
private readonly event: EventEmitter,
private readonly mutex: MutexService
) {}

@Public()
@Post('/create-admin-user')
async createAdmin(
@Req() req: Request,
@Res() res: Response,
@Body() input: CreateUserInput
) {
if (!input.password) {
throw new PasswordRequired();
}

await using lock = await this.mutex.lock('createFirstAdmin');

if (!lock) {
throw new InternalServerError();
}

if ((await this.db.user.count()) > 0) {
throw new ActionForbidden('First user already created');
}

const user = await this.user.createUser({
email: input.email,
password: input.password,
registered: true,
});

try {
await this.event.emitAsync('user.admin.created', user);
await this.auth.setCookie(req, res, user);
res.send({ id: user.id, email: user.email, name: user.name });
} catch (e) {
await this.user.deleteUser(user.id);
throw e;
}
}
}
11 changes: 11 additions & 0 deletions packages/backend/server/src/core/setup/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';

import { AuthModule } from '../auth';
import { UserModule } from '../user';
import { CustomSetupController } from './controller';

@Module({
imports: [AuthModule, UserModule],
controllers: [CustomSetupController],
})
export class CustomSetupModule {}
31 changes: 5 additions & 26 deletions packages/backend/server/src/core/user/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,7 @@ import { PrismaClient } from '@prisma/client';
import GraphQLUpload from 'graphql-upload/GraphQLUpload.mjs';
import { isNil, omitBy } from 'lodash-es';

import {
Config,
CryptoHelper,
type FileUpload,
Throttle,
UserNotFound,
} from '../../fundamentals';
import { type FileUpload, Throttle, UserNotFound } from '../../fundamentals';
import { CurrentUser } from '../auth/current-user';
import { Public } from '../auth/guard';
import { sessionUser } from '../auth/service';
Expand Down Expand Up @@ -177,9 +171,7 @@ class CreateUserInput {
export class UserManagementResolver {
constructor(
private readonly db: PrismaClient,
private readonly user: UserService,
private readonly crypto: CryptoHelper,
private readonly config: Config
private readonly user: UserService
) {}

@Query(() => [UserType], {
Expand Down Expand Up @@ -222,22 +214,9 @@ export class UserManagementResolver {
async createUser(
@Args({ name: 'input', type: () => CreateUserInput }) input: CreateUserInput
) {
validators.assertValidEmail(input.email);
if (input.password) {
const config = await this.config.runtime.fetchAll({
'auth/password.max': true,
'auth/password.min': true,
});
validators.assertValidPassword(input.password, {
max: config['auth/password.max'],
min: config['auth/password.min'],
});
}

const { id } = await this.user.createAnonymousUser(input.email, {
password: input.password
? await this.crypto.encryptPassword(input.password)
: undefined,
const { id } = await this.user.createUser({
email: input.email,
password: input.password,
registered: true,
});

Expand Down
Loading
Loading