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

Use DBOS libraries for ND functions #106

Merged
merged 12 commits into from
Jan 30, 2024
1,712 changes: 875 additions & 837 deletions yky-social/package-lock.json

Large diffs are not rendered by default.

6 changes: 4 additions & 2 deletions yky-social/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"lint": "eslint --fix --ext .ts .",
"tsc": "tsc",
"clean": "rm -rf dist",
"start": "npm run build && dbos start"
"start": "npm run build && dbos-sdk start"
},
"keywords": [],
"author": "",
Expand All @@ -18,7 +18,9 @@
"@aws-sdk/client-s3": "^3.408.0",
"@aws-sdk/s3-presigned-post": "^3.408.0",
"@aws-sdk/s3-request-presigner": "^3.408.0",
"@dbos-inc/dbos-sdk": "^0.8.32-preview",
"@dbos-inc/communicator-bcrypt": "^0.8.53-preview",
"@dbos-inc/communicator-datetime": "^0.8.53-preview",
"@dbos-inc/dbos-sdk": "^0.8.51-preview",
"@koa/bodyparser": "^5.0.0",
"@koa/cors": "^5.0.0",
"@koa/router": "^12.0.0",
Expand Down
30 changes: 8 additions & 22 deletions yky-social/src/YKYOperations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,6 @@ export function errorWithStatus(msg: string, st: number) : ResponseError
return err;
}

async function hashPassword(password: string): Promise<string> {
const saltRounds = 10;
return bcryptjs.hash(password, saltRounds);
}

async function comparePasswords(password: string, hashedPassword: string): Promise<boolean> {
const isMatch = await bcryptjs.compare(password, hashedPassword);
return isMatch;
Expand All @@ -57,28 +52,21 @@ export class Operations

@Transaction()
@RequiredRole([])
static async createUser(ctx: ORMTC, first:string, last:string, uname:string, @SkipLogging pass:string) :
static async createUser(ctx: ORMTC, first:string, last:string, uname:string, @SkipLogging hashpass:string) :
Promise<UserLogin>
{
const manager = ctx.client;

if (!first || !last || !uname || !pass) {
throw errorWithStatus(`Invalid user name or password: ${first}, ${last}, ${uname}, ${pass}`, 400);
if (!first || !last || !uname || !hashpass) {
throw errorWithStatus(`Invalid user name or password: ${first}, ${last}, ${uname}, ${hashpass}`, 400);
}

const user = new UserLogin();
user.first_name = first;
user.last_name = last;
user.user_name = uname;

try
{
user.password_hash = await hashPassword(pass);
}
catch (e)
{
throw errorWithStatus("Password hash failed", 400);
}
user.password_hash = hashpass;

const existingUser = await manager.findOneBy(UserLogin, {
user_name: user.user_name,
Expand Down Expand Up @@ -236,7 +224,7 @@ static async setGraphStatus(ctx: ORMTC, curUid : string, otherUid : string, stat
// Compose a post
// Future: If this takes a long time, split it into a workflow
@Transaction()
static async makePost(ctx: ORMTC, txt : string)
static async makePost(ctx: ORMTC, txt : string, pdate : Date)
{
const manager = ctx.client;

Expand All @@ -247,8 +235,7 @@ static async makePost(ctx: ORMTC, txt : string)
p.author_orignal = ctx.authenticatedUser;
p.media = [];
p.mentions = [];
// eslint-disable-next-line @dbos-inc/detect-new-date
p.post_time = new Date();
p.post_time = pdate; // This could be done in conjunction w/ the datbase
p.post_type = PostType.POST;

const postRep = manager.getRepository(Post);
Expand Down Expand Up @@ -297,7 +284,7 @@ static async distributePost(ctx: ORMTC, p: Post) {
return p;
}

static async makePM(ctx: ORMTC, curUid : string, toUid : string, txt : string) :
static async makePM(ctx: ORMTC, curUid : string, toUid : string, txt : string, mdate: Date) :
Promise<void>
{
// Create post
Expand All @@ -307,8 +294,7 @@ static async makePM(ctx: ORMTC, curUid : string, toUid : string, txt : string) :
p.author_orignal = curUid;
p.media = [];
p.mentions = [toUid];
// eslint-disable-next-line @dbos-inc/detect-new-date
p.post_time = new Date();
p.post_time = mdate;
p.post_type = PostType.PM;

const postRep = ctx.client.getRepository(Post);
Expand Down
11 changes: 8 additions & 3 deletions yky-social/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ import {
DBOSDeploy,
InitContext,
} from "@dbos-inc/dbos-sdk";
import { BcryptCommunicator } from '@dbos-inc/communicator-bcrypt';

import { v4 as uuidv4 } from 'uuid';
import { PresignedPost } from '@aws-sdk/s3-presigned-post';

import { S3Client, S3 } from '@aws-sdk/client-s3';
import { CurrentTimeCommunicator } from '@dbos-inc/communicator-datetime';

function getS3Config(ctx: DBOSContext) {
const s3r = ctx.getConfig('aws_s3_region','us-east-2');
Expand Down Expand Up @@ -190,12 +192,14 @@ export class YKY
// say hey, it's fine, if it all matches?
// Can this be generalized?
@PostApi("/register")
@Workflow()
@RequiredRole([]) // No role needed to register
static async doRegister(ctx: HandlerContext, firstName: string, lastName: string,
static async doRegister(ctx: WorkflowContext, firstName: string, lastName: string,
username: string, @LogMask(LogMasks.HASH) password: string)
{
const hashpass: string = await ctx.invoke(BcryptCommunicator).bcryptHash(password, 10);
const user = await ctx.invoke(Operations).createUser(
firstName, lastName, username, password);
firstName, lastName, username, hashpass);

return { message: 'User created.', id:user.id };
}
Expand All @@ -213,7 +217,8 @@ export class YKY
@Workflow()
@PostApi("/composepost")
static async doCompose(ctx: WorkflowContext, @ArgRequired postText: string) {
const post = await ctx.invoke(Operations).makePost(postText);
const pdate = await ctx.invoke(CurrentTimeCommunicator).getCurrentDate();
const post = await ctx.invoke(Operations).makePost(postText, pdate);
// This could be an asynchronous job
await ctx.invoke(Operations).distributePost(post);
return {message: "Posted."};
Expand Down
2 changes: 2 additions & 0 deletions yky-social/src/operations.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export { YKY } from './app';
export { Operations } from './YKYOperations';
export { CurrentTimeCommunicator } from '@dbos-inc/communicator-datetime';
export { BcryptCommunicator } from '@dbos-inc/communicator-bcrypt';
4 changes: 3 additions & 1 deletion yky-social/src/yky.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ import { YKY } from './app';

import { PresignedPost } from '@aws-sdk/s3-presigned-post';
import { Operations } from './YKYOperations';
import { CurrentTimeCommunicator } from '@dbos-inc/communicator-datetime';
import { BcryptCommunicator } from '@dbos-inc/communicator-bcrypt';

import { TestingRuntime, createTestingRuntime } from '@dbos-inc/dbos-sdk';

let testRuntime: TestingRuntime;

beforeAll(async () => {
testRuntime = await createTestingRuntime([YKY, Operations], "dbos-config.yaml");
testRuntime = await createTestingRuntime([YKY, Operations, CurrentTimeCommunicator, BcryptCommunicator], "dbos-config.yaml");
await testRuntime.createUserSchema();
});

Expand Down
13 changes: 9 additions & 4 deletions yky-social/yky/app/components/RecvTimelineCR.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,25 @@ interface Props {
userid: string;
}

const fetcher = (url: string) => fetch(url).then((res) => res.json());
const fetcher = (url: string) => fetch(url, {
method: 'POST', headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
}).then((res) => res.json());

const RecvTimelineCR: React.FC<Props> = ({ userid }) => {
let rquserid = userid;
if (!rquserid) {
rquserid = 'default';
}

const { data, error, isLoading } = useSWR(`/fetchrtl?rqtimeline=${userid}`,
const { data, error, isLoading } = useSWR(`/fetchrtl`,
fetcher
);

if (error) return "An error has occurred.";
if (isLoading) return "Loading...";
if (error) { return "An error has occurred."; }
if (isLoading) { return "Loading..."; }


const messageList = data.timeline as RecvItem[];
Expand Down
2 changes: 1 addition & 1 deletion yky-social/yky/app/dogetmediakey/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { placeApiRequest } from '@/app/components/backend';

export async function GET(request: NextRequest) {
return await placeApiRequest(request, async (api, req, hdrs) => {
return await api.getProfilePhoto(await req.json(), hdrs);
return await api.getProfilePhoto({}, hdrs);
})
}
2 changes: 1 addition & 1 deletion yky-social/yky/app/doupload/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import { placeApiRequest } from '@/app/components/backend';

export async function GET(request: NextRequest) {
return await placeApiRequest(request, async (api, req, hdrs) => {
return await api.doStartMediaUpload(await req.json(), hdrs);
return await api.doStartMediaUpload({}, hdrs);
})
}
2 changes: 1 addition & 1 deletion yky-social/yky/app/fetchrtl/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextRequest } from 'next/server';

import { placeApiRequest } from '@/app/components/backend';

export async function GET(request: NextRequest) {
export async function POST(request: NextRequest) {
return placeApiRequest(request, async (api, req, hdrs) => {
return await api.receiveTimeline(await req.json(), hdrs);
});
Expand Down
2 changes: 1 addition & 1 deletion yky-social/yky/app/fetchstl/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { placeApiRequest } from '@/app/components/backend';

export async function GET(request: NextRequest) {
return placeApiRequest(request, async (api, req, hdrs) => {
return await api.sendTimeline(await req.json(), hdrs);
return await api.sendTimeline({}, hdrs);
});
}
4 changes: 2 additions & 2 deletions yky-social/yky/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"dev": "next dev -p 3030",
"build": "next build",
"start": "next start -p 3001",
"start": "next start -p 3030",
"lint": "next lint --fix"
},
"dependencies": {
Expand Down
Loading