Open-source and local-first Slack and Notion alternative that puts you in control of your data
TypeScript chatchat-applicationcrdteditorelectronknowledge-baselocal-firstnotionnotion-alternativerealtime-collaborationself-hostedslacksqliteteam-collaborationwikiyjs
Implement workspace tables
Hakan Shehu14dbd2e80fd1
diff --git a/server/prisma/migrations/20240729132547_workspaces/migration.sql b/server/prisma/migrations/20240729132547_workspaces/migration.sqlnew file mode 100644index 00000000..8ec04e03--- /dev/null+++ b/server/prisma/migrations/20240729132547_workspaces/migration.sql@@ -0,0 +1,46 @@+-- CreateTable+CREATE TABLE "accounts" (+ "id" VARCHAR(30) NOT NULL,+ "name" VARCHAR(256) NOT NULL,+ "email" VARCHAR(256) NOT NULL,+ "avatar" VARCHAR(256),+ "password" VARCHAR(256),+ "attrs" JSONB DEFAULT 'null',+ "created_at" TIMESTAMPTZ(6) NOT NULL,+ "updated_at" TIMESTAMPTZ(6),+ "status" INTEGER NOT NULL,++ CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "workspaces" (+ "id" VARCHAR(30) NOT NULL,+ "name" VARCHAR(256) NOT NULL,+ "attrs" JSONB DEFAULT 'null',+ "created_at" TIMESTAMPTZ(6) NOT NULL,+ "created_by" VARCHAR(30) NOT NULL,+ "updated_at" TIMESTAMPTZ(6),+ "updated_by" VARCHAR(30),+ "status" INTEGER NOT NULL,++ CONSTRAINT "workspaces_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "workspace_accounts" (+ "workspace_id" VARCHAR(30) NOT NULL,+ "account_id" VARCHAR(30) NOT NULL,+ "role" INTEGER NOT NULL,+ "attrs" JSONB DEFAULT 'null',+ "created_at" TIMESTAMPTZ(6) NOT NULL,+ "created_by" VARCHAR(30) NOT NULL,+ "updated_at" TIMESTAMPTZ(6),+ "updated_by" VARCHAR(30),+ "status" INTEGER NOT NULL,++ CONSTRAINT "workspace_accounts_pkey" PRIMARY KEY ("workspace_id","account_id")+);++-- CreateIndex+CREATE UNIQUE INDEX "IX_accounts_email" ON "accounts"("email");diff --git a/server/prisma/migrations/migration_lock.toml b/server/prisma/migrations/migration_lock.tomlnew file mode 100644index 00000000..fbffa92c--- /dev/null+++ b/server/prisma/migrations/migration_lock.toml@@ -0,0 +1,3 @@+# Please do not edit this file manually+# It should be added in your version-control system (i.e. Git)+provider = "postgresql"\ No newline at end of filediff --git a/server/prisma/schema.prisma b/server/prisma/schema.prismaindex 2e8c5b8e..22a42f84 100644--- a/server/prisma/schema.prisma+++ b/server/prisma/schema.prisma@@ -18,3 +18,29 @@ model accounts {updatedAt DateTime? @db.Timestamptz(6) @map("updated_at")status Int}++model workspaces {+ id String @id @db.VarChar(30)+ name String @db.VarChar(256)+ attrs Json? @default("null")+ createdAt DateTime @db.Timestamptz(6) @map("created_at")+ createdBy String @db.VarChar(30) @map("created_by")+ updatedAt DateTime? @db.Timestamptz(6) @map("updated_at")+ updatedBy String? @db.VarChar(30) @map("updated_by")+ status Int+}++model workspaceAccounts {+ workspaceId String @db.VarChar(30) @map("workspace_id")+ accountId String @db.VarChar(30) @map("account_id")+ role Int+ attrs Json? @default("null")+ createdAt DateTime @db.Timestamptz(6) @map("created_at")+ createdBy String @db.VarChar(30) @map("created_by")+ updatedAt DateTime? @db.Timestamptz(6) @map("updated_at")+ updatedBy String? @db.VarChar(30) @map("updated_by")+ status Int++ @@map("workspace_accounts")+ @@id([workspaceId, accountId])+}\ No newline at end of filediff --git a/server/src/index.ts b/server/src/index.tsindex 1a5eafbf..0ffde299 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -1,5 +1,6 @@import express, { Request, Response } from 'express';-import {accounts} from "./routes/accounts";+import {accounts} from "@/routes/accounts";+import {workspaces} from "@/routes/workspaces";const app = express();const port = 3000;@@ -15,6 +16,12 @@ app.post('/v1/accounts/login/google', accounts.loginWithGoogle);app.post('/v1/accounts/login/email', accounts.loginWithEmail);app.post('/v1/accounts/register/email', accounts.registerWithEmail);+//workspaces+app.post('/v1/workspaces', workspaces.createWorkspace);+app.put('/v1/workspaces/:id', workspaces.updateWorkspace);+app.delete('/v1/workspaces/:id', workspaces.deleteWorkspace);+app.get('/v1/workspaces/:id', workspaces.getWorkspace);+app.listen(port, () => {console.log(`Server is running at http://localhost:${port}`);});diff --git a/server/src/lib/id.ts b/server/src/lib/id.tsindex b05c5b05..3a880a7b 100644--- a/server/src/lib/id.ts+++ b/server/src/lib/id.ts@@ -8,4 +8,5 @@ export function generateId(type: IdType) {export enum IdType {Account = 'ac',+ Workspace = 'wc'}\ No newline at end of filediff --git a/server/src/routes/accounts.ts b/server/src/routes/accounts.tsindex b274d4e2..ad85f4d3 100644--- a/server/src/routes/accounts.ts+++ b/server/src/routes/accounts.ts@@ -1,6 +1,5 @@import {Request, Response} from "express";import {- Account,AccountStatus, EmailLoginInput,EmailRegisterInput,GoogleLoginInput,@@ -9,26 +8,28 @@ import {} from "@/types/accounts";import axios from "axios";import {ApiError} from "@/types/api";-import {createAccount, findAccountByEmail, hashPassword, updateGoogleId, verifyPassword} from "@/services/accounts";import {generateId, IdType} from "@/lib/id";import jwt from "jsonwebtoken";+import {prisma} from "@/data/db";+import bcrypt from "bcrypt";const GoogleUserInfoUrl = "https://www.googleapis.com/oauth2/v1/userinfo";const JwtSecretKey = process.env.JWT_SECRET ?? '';const JwtAudience = process.env.JWT_AUDIENCE ?? '';const JwtIssuer = process.env.JWT_ISSUER ?? '';+const SaltRounds = 10;-function buildLoginOutput(account: Account): LoginOutput {+function buildLoginOutput(id: string, name: string, email: string): LoginOutput {const signOptions: jwt.SignOptions = {issuer: JwtIssuer,audience: JwtAudience,- subject: account.id,+ subject: id,expiresIn: '1y',};const payload = {- name: account.name,- email: account.email,+ name: name,+ email: email,};const token = jwt.sign(payload, JwtSecretKey, signOptions);@@ -40,56 +41,71 @@ function buildLoginOutput(account: Account): LoginOutput {async function registerWithEmail(req: Request, res: Response) {const input: EmailRegisterInput = req.body;- let existingUser = await findAccountByEmail(input.email);+ let existingAccount = await prisma+ .accounts+ .findUnique({+ where: {+ email: input.email+ }+ });- if (existingUser) {+ if (existingAccount) {return res.status(400).json({code: ApiError.EmailAlreadyExists,message: "Email already exists."});}- const password = await hashPassword(input.password);- const account: Account = {- id: generateId(IdType.Account),- name: input.name,- email: input.email,- password: password,- status: AccountStatus.Active,- createdAt: new Date(),- };+ const salt = await bcrypt.genSalt(SaltRounds);+ const password = await bcrypt.hash(input.password, salt);+ const account = await prisma+ .accounts+ .create({+ data: {+ id: generateId(IdType.Account),+ name: input.name,+ email: input.email,+ password: password,+ status: AccountStatus.Active,+ createdAt: new Date(),+ }+ });- await createAccount(account);- return res.json(buildLoginOutput(account));+ return res.json(buildLoginOutput(account.id, account.name, account.email));}async function loginWithEmail(req: Request, res: Response) {const input: EmailLoginInput = req.body;- let existingUser = await findAccountByEmail(input.email);+ let account = await prisma+ .accounts+ .findUnique({+ where: {+ email: input.email+ }+ });- if (!existingUser) {+ if (!account) {return res.status(400).json({code: ApiError.EmailOrPasswordIncorrect,message: "Invalid credentials."});}- if (existingUser.status === AccountStatus.Pending) {+ if (account.status === AccountStatus.Pending) {return res.status(400).json({code: ApiError.UserPendingActivation,message: "User is pending activation."});}- if (!existingUser.password) {+ if (!account.password) {return res.status(400).json({code: ApiError.EmailOrPasswordIncorrect,message: "Invalid credentials."});}- let passwordMatch = await verifyPassword(input.password, existingUser.password);-+ const passwordMatch = await bcrypt.compare(input.password, account.password);if (!passwordMatch) {return res.status(400).json({code: ApiError.EmailOrPasswordIncorrect,@@ -97,7 +113,7 @@ async function loginWithEmail(req: Request, res: Response) {});}- return res.json(buildLoginOutput(existingUser));+ return res.json(buildLoginOutput(account.id, account.name, account.email));}async function loginWithGoogle(req: Request, res: Response) {@@ -121,33 +137,53 @@ async function loginWithGoogle(req: Request, res: Response) {});}- let existingUser = await findAccountByEmail(googleUser.email);+ let existingAccount = await prisma+ .accounts+ .findUnique({+ where: {+ email: googleUser.email+ }+ });- if (existingUser) {- if (existingUser.status === AccountStatus.Pending) {+ if (existingAccount) {+ if (existingAccount.status === AccountStatus.Pending) {return res.status(400).json({code: ApiError.UserPendingActivation,message: "User is pending activation."});}- await updateGoogleId(existingUser.id, googleUser.id);- return res.json(buildLoginOutput(existingUser));+ const attrs = existingAccount.attrs as Record<string, any> ?? {};+ if (attrs?.googleId) {+ await prisma+ .accounts+ .update({+ where: {+ id: existingAccount.id+ },+ data: {+ attrs: { googleId: googleUser.id },+ updatedAt: new Date()+ }+ });+ }++ return res.json(buildLoginOutput(existingAccount.id, existingAccount.name, existingAccount.email));}- const account: Account = {- id: generateId(IdType.Account),- name: googleUser.name,- email: googleUser.email,- status: AccountStatus.Active,- createdAt: new Date(),- attrs: {- googleId: googleUser.id- }- };+ const newAccount = await prisma+ .accounts+ .create({+ data: {+ id: generateId(IdType.Account),+ name: googleUser.name,+ email: googleUser.email,+ status: AccountStatus.Active,+ createdAt: new Date(),+ }+ });- await createAccount(account);- return res.json(buildLoginOutput(account));+ return res.json(buildLoginOutput(newAccount.id, newAccount.name, newAccount.email));}export const accounts = {diff --git a/server/src/routes/workspaces.ts b/server/src/routes/workspaces.tsnew file mode 100644index 00000000..6e04aa08--- /dev/null+++ b/server/src/routes/workspaces.ts@@ -0,0 +1,138 @@+import {Request, Response} from "express";+import {WorkspaceInput} from "@/types/workspaces";+import {ApiError} from "@/types/api";+import {generateId, IdType} from "@/lib/id";+import {prisma} from "@/data/db";++async function createWorkspace(req: Request, res: Response) {+ const input: WorkspaceInput = req.body;++ if (!input.name) {+ return res.status(400).json({+ code: ApiError.MissingRequiredFields,+ message: "Missing required fields."+ });+ }++ const workspace = await prisma+ .workspaces+ .create({+ data: {+ id: generateId(IdType.Workspace),+ name: input.name,+ createdAt: new Date(),+ createdBy: 'user-id',+ status: 1,+ }+ });++ return res.json({+ id: workspace.id,+ name: workspace.name,+ createdAt: workspace.createdAt+ });+}++async function updateWorkspace(req: Request, res: Response) {+ const id = req.params.id;+ const input: WorkspaceInput = req.body;++ const workspace = await prisma+ .workspaces+ .findUnique({+ where: {+ id: id+ }+ });++ if (!workspace) {+ return res.status(404).json({+ code: ApiError.ResourceNotFound,+ message: "Workspace not found."+ });+ }++ const updatedWorkspace = await prisma+ .workspaces+ .update({+ where: {+ id: id+ },+ data: {+ name: input.name,+ updatedAt: new Date(),+ updatedBy: 'user-id'+ }+ });++ return res.json({+ id: updatedWorkspace.id,+ name: updatedWorkspace.name,+ createdAt: updatedWorkspace.createdAt+ });+}++async function deleteWorkspace(req: Request, res: Response) {+ const id = req.params.id;++ const workspace = await prisma+ .workspaces+ .findUnique({+ where: {+ id: id+ }+ });++ if (!workspace) {+ return res.status(404).json({+ code: ApiError.ResourceNotFound,+ message: "Workspace not found."+ });+ }++ await prisma+ .workspaces+ .delete({+ where: {+ id: id+ }+ });++ return res.json({+ id: workspace.id,+ name: workspace.name,+ createdAt: workspace.createdAt+ });+}++async function getWorkspace(req: Request, res: Response) {+ const id = req.params.id;++ const workspace = await prisma+ .workspaces+ .findUnique({+ where: {+ id: id+ }+ });++ if (!workspace) {+ return res.status(404).json({+ code: ApiError.ResourceNotFound,+ message: "Workspace not found."+ });+ }++ return res.json({+ id: workspace.id,+ name: workspace.name,+ createdAt: workspace.createdAt+ });+}++export const workspaces = {+ createWorkspace,+ updateWorkspace,+ deleteWorkspace,+ getWorkspace+}\ No newline at end of filediff --git a/server/src/services/accounts.ts b/server/src/services/accounts.tsdeleted file mode 100644index 84b6a2bf..00000000--- a/server/src/services/accounts.ts+++ /dev/null@@ -1,80 +0,0 @@-import {prisma} from "@/data/db";-import {Account} from "@/types/accounts";-import bcrypt from 'bcrypt';--const SaltRounds = 10;--export async function findAccountByEmail(email: string): Promise<Account | null> {- const account = await prisma- .accounts- .findUnique({- where: {- }- });-- if (!account) {- return null;- }-- return {- id: account.id,- name: account.name,- email: account.email,- password: account.password,- createdAt: account.createdAt,- updatedAt: account.updatedAt,- status: account.status,- attrs: account.attrs as Record<string, any>,- };-}--export async function updateGoogleId(accountId: string, googleId: string): Promise<void> {- await prisma- .accounts- .update({- where: {- id: accountId- },- data: {- attrs: { googleId },- updatedAt: new Date()- }- });-}--export async function createAccount(account: Account): Promise<Account> {- const newAccount = await prisma- .accounts- .create({- data: {- id: account.id,- name: account.name,- email: account.email,- password: account.password,- createdAt: account.createdAt,- status: account.status,- attrs: account.attrs- }- });-- return {- id: newAccount.id,- name: newAccount.name,- email: newAccount.email,- password: newAccount.password,- createdAt: newAccount.createdAt,- updatedAt: newAccount.updatedAt,- status: newAccount.status,- attrs: newAccount.attrs as Record<string, any>,- };-}--export async function hashPassword(password: string): Promise<string> {- const salt = await bcrypt.genSalt(SaltRounds);- return await bcrypt.hash(password, salt);-}--export async function verifyPassword(password: string, hash: string): Promise<boolean> {- return await bcrypt.compare(password, hash);-}diff --git a/server/src/types/api.ts b/server/src/types/api.tsindex 99055c50..da740507 100644--- a/server/src/types/api.ts+++ b/server/src/types/api.ts@@ -4,4 +4,6 @@ export enum ApiError {InternalServerError = "InternalServerError",EmailAlreadyExists = "EmailAlreadyExists",EmailOrPasswordIncorrect = "EmailOrPasswordIncorrect",+ MissingRequiredFields = "MissingRequiredFields",+ ResourceNotFound = "ResourceNotFound"}diff --git a/server/src/types/workspaces.ts b/server/src/types/workspaces.tsnew file mode 100644index 00000000..38475b83--- /dev/null+++ b/server/src/types/workspaces.ts@@ -0,0 +1,27 @@+export enum WorkspaceStatus {+ Active = 1,+ Inactive = 2+}++export type Workspace = {+ id: string;+ name: string;+ description?: string | null;+ createdAt: Date;+ createdBy: string;+ updatedAt?: Date | null;+ updatedBy?: string | null;+ status: WorkspaceStatus;+};++export type WorkspaceInput = {+ name: string;+ description?: string | null;+};++export type WorkspaceOutput = {+ id: string;+ name: string;+ description?: string | null;+ createdAt: Date;+};\ No newline at end of file