Skip to content

Commit

Permalink
fix: resolve errors that thrown as following the installation guide o…
Browse files Browse the repository at this point in the history
…n docs.namviek.com (#173)
  • Loading branch information
hudy9x authored May 12, 2024
1 parent e268d82 commit 3b10a79
Show file tree
Hide file tree
Showing 39 changed files with 599 additions and 612 deletions.
43 changes: 27 additions & 16 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
DEV_MODE=true
DEV_MODE=1
DEFAULT_PWD=123123123
NEXT_PUBLIC_FE_GATEWAY=http://localhost:4200/
NEXT_PUBLIC_BE_GATEWAY=http://localhost:3333/
NEXT_PUBLIC_APP_NAME=Namviek

MONGODB_URL=
MONGODB_URL=mongodb+srv://{user}:{pwd}@cluster0.wd3az.mongodb.net/{dbName}?retryWrites=true&w=majority

JWT_SECRET_KEY=12GUY3N76U21d4IJ
JWT_REFRESH_KEY=7us9s88o121ieeuo
JWT_VERIFY_USER_LINK_TOKEN_EXPIRED=1h

JWT_TOKEN_EXPIRED=30m
JWT_REFRESH_EXPIRED=4h

REDIS_HOST=
# Visit https://resend.com/api-keys to get API key

RESEND_TOKEN=
RESEND_EMAIL_DOMAIN=

# AWS s3 token
AWS_ACCESS_KEY=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=ap-southeast-1
AWS_S3_BUCKET=kampunistore

# Replicate Api Token: https://replicate.com/meta/llama-2-70b-chat/api
REPLICATE_API_TOKEN=

# Open API Key
OPEN_API_KEY=

JWT_VERIFY_USER_LINK_TOKEN_EXPIRED=1h
RESEND_EMAIL_DOMAIN=namviek.com
NEXT_PUBLIC_FE_GATEWAY=http://localhost:4200/
AWS_REGION=
AWS_S3_BUCKET=

# Pusher notification
NEXT_PUBLIC_PUSHER_INSTANCE_ID=
PUSHER_INSTANCE_ID=
PUSHER_SECRET_KEY=

# Pusher channels
NEXT_PUBLIC_PUSHER_CHANNEL_APP_KEY=
NEXT_PUBLIC_PUSHER_CHANNEL_APP_CLUSTER=
PUSHER_CHANNEL_APP_ID=
PUSHER_CHANNEL_SECRET=

# Livekit
LIVEKIT_API_KEY=
LIVEKIT_API_SECRET=
NEXT_PUBLIC_LIVEKIT_URL=

FIREBASE_PROJECT_ID=
FIREBASE_CLIENT_EMAIL=
FIREBASE_PRIVATE_KEY=
NEXT_PUBLIC_FIREBASE_CLIENT_CONFIG=


8 changes: 4 additions & 4 deletions DOCUMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ We're using Pusher/channel to push a message from server to client. For instance
- When a user type a new comment, the other user will receive this comment immediately.
- Or when a new user was added to a new project, he/she will be see it right after the manager update member list

To use it, in your backend code, import the `pusherServer` and trigger an event as follows:
To use it, in your backend code, import the `pusherTrigger` and trigger an event as follows:
```javascript
import { pusherServer } from '../../lib/pusher-server'
import { pusherTrigger } from '../../lib/pusher-server'

const eventName = `event-delete-task-comment`

pusherServer.trigger('team-collab', eventName, {
pusherTrigger('team-collab', eventName, {
id,
triggerBy: updatedBy
})
Expand Down Expand Up @@ -93,4 +93,4 @@ NEXT_PUBLIC_LIVEKIT_URL|wss://namviek-hmunmehy.livekit.cloud|Livekit url||
|-|-|-|-|
|FIREBASE_PROJECT_ID|namviek-4234|Project id||
|FIREBASE_CLIENT_EMAIL|[email protected]|Client email generated by Firebase||
|FIREBASE_PRIVATE_KEY||Firebase private key||
|FIREBASE_PRIVATE_KEY||Firebase private key||
12 changes: 11 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,27 @@
"frontend": "nx serve ui-app",
"backend": "nx serve be-gateway",
"scheduler": "nx serve be-scheduler",

"build:fe": "nx build ui-app --prod --skip-nx-cache",
"build:be": "nx build be-gateway --prod --skip-nx-cache",
"build:se": "nx build be-scheduler --prod --skip-nx-cache",
"build:all": "yarn build:fe && yarn build:be",

"prod:fe": "next start ./dist/packages/ui-app/",
"prod:be": "node ./dist/packages/be-gateway/main.js",
"prod:se": "node ./dist/packages/be-scheduler/main.js",

"prisma": "prisma",

"generate": "prisma generate --schema=.\\packages\\shared-models\\src\\prisma\\schema.prisma",
"pushdb": "prisma db push --schema=.\\packages\\shared-models\\src\\prisma\\schema.prisma",
"seed": "prisma db seed --schema=.\\packages\\shared-models\\src\\prisma\\schema.prisma",

"generate2": "prisma generate --schema=./packages/shared-models/src/prisma/schema.prisma",
"postinstall": "prisma generate"
"pushdb2": "prisma db push --schema=./packages/shared-models/src/prisma/schema.prisma",
"seed2": "prisma db seed --schema=./packages/shared-models/src/prisma/schema.prisma",

"postinstall": "yarn generate2"
},
"private": true,
"dependencies": {
Expand Down
26 changes: 13 additions & 13 deletions packages/be-gateway/src/core/AppRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const AppRoutes = (routeControllers: any[]) => {

routeControllers.forEach(controller => {
const instance = new controller()
console.log('================')
// console.log('================')

const prefix = getMetadata(MetaKey.PREFIX, controller) as string
const routes = getMetadata(MetaKey.ROUTES, controller) as RouteDefinition[]
Expand Down Expand Up @@ -50,12 +50,12 @@ export const AppRoutes = (routeControllers: any[]) => {
if (!func) return

if (params && params.length) {
console.log(
method.toUpperCase(),
`${prefix}${path}`,
'==>',
r.methodName
)
// console.log(
// method.toUpperCase(),
// `${prefix}${path}`,
// '==>',
// r.methodName
// )
// console.log(params)

methodRouter[method](path, async (req, res, next) => {
Expand Down Expand Up @@ -105,12 +105,12 @@ export const AppRoutes = (routeControllers: any[]) => {
}
})
} else {
console.log(
method.toUpperCase(),
`${prefix}${path}`,
'==>',
r.methodName
)
// console.log(
// method.toUpperCase(),
// `${prefix}${path}`,
// '==>',
// r.methodName
// )
methodRouter[method](path, async (req, res, next) => {
instance.req = req
instance.res = res
Expand Down
4 changes: 2 additions & 2 deletions packages/be-gateway/src/jobs/status.pusher.job.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pusherServer } from '../lib/pusher-server'
import { pusherTrigger } from '../lib/pusher-server'

export default class StatusPusherJob {
async triggerUpdateEvent({
Expand All @@ -8,7 +8,7 @@ export default class StatusPusherJob {
projectId: string
uid: string
}) {
pusherServer.trigger('team-collab', `projectStatus:update-${projectId}`, {
pusherTrigger('team-collab', `projectStatus:update-${projectId}`, {
triggerBy: uid
})
}
Expand Down
4 changes: 2 additions & 2 deletions packages/be-gateway/src/jobs/task.pusher.job.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pusherServer } from '../lib/pusher-server'
import { pusherTrigger } from '../lib/pusher-server'

export default class TaskPusherJob {
async triggerUpdateEvent({
Expand All @@ -8,7 +8,7 @@ export default class TaskPusherJob {
projectId: string
uid: string
}) {
pusherServer.trigger('team-collab', `projectTask:update-${projectId}`, {
pusherTrigger('team-collab', `projectTask:update-${projectId}`, {
triggerBy: uid
})
}
Expand Down
35 changes: 31 additions & 4 deletions packages/be-gateway/src/lib/buzzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,37 @@ import PushNotifications, {
} from '@pusher/push-notifications-server'
import { getLogoUrl } from './url'

const beamsClient = new PushNotifications({
instanceId: process.env.PUSHER_INSTANCE_ID,
secretKey: process.env.PUSHER_SECRET_KEY
})
let beamsClient: PushNotifications
let ready = false
const throwErrMess = () => console.warn('Pusher beams secret is missing')

try {
const pusherConfig = {
instanceId: process.env.PUSHER_INSTANCE_ID,
secretKey: process.env.PUSHER_SECRET_KEY
}
if (Object.values(pusherConfig).every(Boolean)) {
beamsClient = new PushNotifications(pusherConfig)
ready = true
} else {
throwErrMess()
}

} catch (error) {
throwErrMess()
}

const _cannotPushNotification = () => {
if (!ready) {
throwErrMess()
return true
}

return false
}

export const generateBuzzerToken = (uid: string) => {
if (_cannotPushNotification()) return
const beamsToken = beamsClient.generateToken(uid)
return beamsToken
}
Expand All @@ -17,6 +42,7 @@ export const notifyToUsers = (
uid: string | string[],
opts: PushNotifications.PublishRequest
) => {
if (_cannotPushNotification()) return
const uids = Array.isArray(uid) ? uid : [uid]
return beamsClient.publishToUsers(uids, opts)
}
Expand All @@ -25,6 +51,7 @@ export const notifyToWebUsers = (
uid: string | string[],
opts: WebNotificationPayload
) => {
if (_cannotPushNotification()) return
console.log('notify to web users', uid, opts)
const uids = Array.isArray(uid) ? uid : [uid]

Expand Down
22 changes: 21 additions & 1 deletion packages/be-gateway/src/lib/email.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { Resend } from 'resend'
const resend = new Resend(process.env.RESEND_TOKEN)
let resend: Resend;
let ready = false
try {
resend = new Resend(process.env.RESEND_TOKEN)
ready = true
} catch (error) {
console.warn("Resend token is missing")
}

const supportEmail = 'support.dev'
const productionAddress = 'Kampuni.dev'
Expand All @@ -11,7 +18,18 @@ interface IEmailFields {
emails: string[]
}

const _cannotSendEmail = () => {
if (!ready) {
console.warn('Cannot send this email. Resend token is missing')
return true
}

return false
}


export const sendEmail = ({ emails, html, subject }: IEmailFields) => {
if (_cannotSendEmail()) return
return resend.emails.send({
from: `Noreply <noreply@${process.env.RESEND_EMAIL_DOMAIN}>`,
to: emails,
Expand Down Expand Up @@ -44,6 +62,8 @@ export const sendVerifyEmail = ({
email: string
token: string
}) => {
if (_cannotSendEmail()) return

const verificationLink = `${process.env.NEXT_PUBLIC_FE_GATEWAY}email-verification?token=${token}`
return sendEmail({
emails: [email],
Expand Down
22 changes: 13 additions & 9 deletions packages/be-gateway/src/lib/firebase-admin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { cert, initializeApp, getApps } from 'firebase-admin/app'

const serviceAccount = {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')
}
try {
const serviceAccount = {
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')
}

if (!getApps().length) {
initializeApp({
credential: cert(serviceAccount)
})
if (!getApps().length) {
initializeApp({
credential: cert(serviceAccount)
})
}
} catch (error) {
console.warn('Firebase admin missing configuration')
}
14 changes: 0 additions & 14 deletions packages/be-gateway/src/lib/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,6 @@ import { createLogger, format, transports } from 'winston'

const { combine, timestamp, label, prettyPrint, simple } = format

// const logger = createLogger({
// format: combine(label({ label: '' }), timestamp(), prettyPrint()),
// transports: [
// new transports.Console({ format: simple() }),
// new transports.File({ filename: '/home/bitnami/logs/backend.log' })
// ]
// })

// export const logging = logger

export const createModuleLog = (module: string) => {
return createLogger({
format: combine(label({ label: module }), timestamp(), prettyPrint()),
Expand All @@ -25,7 +15,3 @@ export const createModuleLog = (module: string) => {
})
}

// import { Logtail } from '@logtail/node'
//
// const logtail = new Logtail(process.env.LOGTAIL_SOURCE_TOKEN)
// export const Log = logtail
14 changes: 11 additions & 3 deletions packages/be-gateway/src/lib/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ import { compareSync, genSaltSync, hashSync } from 'bcryptjs'
import { isDevMode } from './utils'

const salt = genSaltSync(10)
const defaultPwd = process.env.DEFAULT_PWD

export const hashPassword = (pwd: string) => {
return hashSync(pwd, salt)
}

export const compareHashPassword = (pwd: string, hashedPwd: string) => {
if (isDevMode() && pwd === '123123123') {
return true
let valid = false
if (compareSync(pwd, hashedPwd)) {
valid = true
}
return compareSync(pwd, hashedPwd)

// in development mode, any user can access with their own password and default password
if (!valid && isDevMode() && defaultPwd && pwd === defaultPwd) {
valid = true
}

return valid
}
Loading

0 comments on commit 3b10a79

Please sign in to comment.