adding in old api
This commit is contained in:
@@ -0,0 +1,216 @@
|
||||
import { JwtClaims, authCheck } from '../middleware/auth';
|
||||
import { Line, LineMember, LineMemberState } from '@nirvana/core/models/line.model';
|
||||
import express, { Application, Request, Response } from 'express';
|
||||
|
||||
import Content from '@nirvana/core/models/content.model';
|
||||
import CreateLineRequest from '@nirvana/core/requests/createLine.request';
|
||||
import GetConversationDetailsResponse from '@nirvana/core/responses/getConversationDetails.response';
|
||||
import GetDmConversationByOtherUserIdResponse from '@nirvana/core/responses/getDmConversationByOtherUserId.response';
|
||||
import GetUserLinesResponse from '@nirvana/core/responses/getUserLines.response';
|
||||
import { LineService } from '../services/line.service';
|
||||
import MasterLineData from '@nirvana/core/models/masterLineData.model';
|
||||
import NirvanaResponse from '@nirvana/core/responses/nirvanaResponse';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import Relationship from '@nirvana/core/models/relationship.model';
|
||||
import { User } from '@nirvana/core/models/user.model';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { collections } from '../services/database.service';
|
||||
import UpdateLineMemberState from '@nirvana/core/requests/updateLineMemberState.request';
|
||||
|
||||
export default function getLineRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// get data for a one on one conversation
|
||||
// router.get("/:otherUserGoogleUserId", authCheck, getConversationDetails);
|
||||
|
||||
// create a line
|
||||
router.post('/', authCheck, createLine);
|
||||
|
||||
// get all of user's lines
|
||||
router.get('/', authCheck, getUserLines);
|
||||
|
||||
// toggle tune into a line
|
||||
router.post('/:lineId/state', authCheck, updateLineMemberState);
|
||||
|
||||
// get conversation between user and other user
|
||||
router.get('/dm/:otherUserId', authCheck, getDmByOtherUserId);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
async function getDmByOtherUserId(req: Request, res: Response) {
|
||||
try {
|
||||
const { otherUserId } = req.params;
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
console.log(otherUserId);
|
||||
|
||||
// check db for lines between me and this other person
|
||||
// if there is one, then return it with 200 status
|
||||
// else return it with custom status that frontend will read
|
||||
|
||||
res.status(200).json();
|
||||
return;
|
||||
|
||||
res.status(205).json('no such conversation between you two');
|
||||
} catch (error) {
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function createLine(req: Request, res: Response) {
|
||||
try {
|
||||
const reqObj: CreateLineRequest = req.body as CreateLineRequest;
|
||||
console.log(req.body);
|
||||
|
||||
if (!reqObj?.otherMemberIds.length) {
|
||||
res.status(400).json('must provide member Ids');
|
||||
return;
|
||||
}
|
||||
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
const newLine = new Line(
|
||||
new ObjectId(userInfo.userId),
|
||||
reqObj.lineName ?? undefined,
|
||||
new Date(),
|
||||
new Date(),
|
||||
new ObjectId(),
|
||||
);
|
||||
|
||||
// TODO: validate that users exists before creating line members
|
||||
const lineMembers: LineMember[] =
|
||||
reqObj.otherMemberIds.map((memId) => {
|
||||
const newLineMember = new LineMember(
|
||||
newLine._id!,
|
||||
new ObjectId(memId),
|
||||
LineMemberState.INBOX,
|
||||
);
|
||||
|
||||
return newLineMember;
|
||||
}) ?? [];
|
||||
|
||||
lineMembers.push(
|
||||
new LineMember(newLine._id!, new ObjectId(userInfo.userId), LineMemberState.INBOX),
|
||||
);
|
||||
|
||||
const transactionResult = await LineService.createLine(newLine, lineMembers);
|
||||
|
||||
transactionResult
|
||||
? res.status(200).json(new NirvanaResponse(newLine))
|
||||
: res.status(400).json(new NirvanaResponse(undefined, new Error('unable to create line')));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLineMemberState(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
const { lineId } = req.params;
|
||||
const request = req.body as UpdateLineMemberState;
|
||||
|
||||
// TODO: validation to check if user is actually a member of the line
|
||||
|
||||
const result = await LineService.updateLineMemberState(
|
||||
lineId,
|
||||
userInfo.userId,
|
||||
request.newState,
|
||||
);
|
||||
|
||||
return result?.ok
|
||||
? res.status(200).json(new NirvanaResponse("successfully updated line member's state"))
|
||||
: res
|
||||
.status(400)
|
||||
.json(new NirvanaResponse(undefined, new Error('not updated...something went wrong')));
|
||||
} catch (error) {
|
||||
res.status(500).json(new NirvanaResponse(undefined, error as Error));
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserLines(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
// get all of user's lineMember entries
|
||||
const userLineMembers = await LineService.getLineMembersByUserId(userInfo.userId);
|
||||
|
||||
if (!userLineMembers?.length) {
|
||||
const resObj = new GetUserLinesResponse([]);
|
||||
|
||||
res.json(new NirvanaResponse(resObj, undefined, 'this user is not in any lines'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const lineIds = userLineMembers?.map((lineMember) => lineMember.lineId) ?? [];
|
||||
|
||||
// this will include the current user lineMember association to the line
|
||||
const allLineMembers = await LineService.getLineMembersInLines(lineIds);
|
||||
|
||||
const allLinesUsersIds: ObjectId[] = [];
|
||||
allLineMembers?.map((currentLineMember) => {
|
||||
if (currentLineMember?.userId) allLinesUsersIds.push(currentLineMember.userId);
|
||||
}) ?? [];
|
||||
|
||||
// get all users relevant here
|
||||
const allRelevantUsers = await UserService.getUsersByIds(allLinesUsersIds);
|
||||
|
||||
// get all lines from the list of relevant lines
|
||||
const lines = (await LineService.getLinesByIds(lineIds)) ?? [];
|
||||
|
||||
const masterLines: MasterLineData[] = [];
|
||||
|
||||
// TODO: get the latest audio blocks for this line...maybe like today and yesterday or by block count
|
||||
|
||||
lines.map((currentLine) => {
|
||||
let associatedLineMembersForLine: LineMember[] = [];
|
||||
|
||||
// get all of the line members for this Line
|
||||
// make sure that we don't add line member if it's the current user
|
||||
allLineMembers?.map((lineMember) => {
|
||||
if (currentLine._id) {
|
||||
if (lineMember.lineId.equals(currentLine._id))
|
||||
associatedLineMembersForLine.push(lineMember);
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
// get the user lineMember assoc out of the list of the lineMembers for this line
|
||||
const userLineMember = associatedLineMembersForLine?.find(
|
||||
(currentLineMemberForLine) =>
|
||||
currentLineMemberForLine.userId.toString() === userInfo.userId,
|
||||
);
|
||||
|
||||
if (userLineMember) {
|
||||
// take out the current user from the "other" line members list now
|
||||
|
||||
associatedLineMembersForLine = associatedLineMembersForLine.filter(
|
||||
(currentLineMember) => currentLineMember.userId.toString() !== userInfo.userId,
|
||||
);
|
||||
|
||||
// get the user objects for all of the other members
|
||||
const otherUsers: User[] = [];
|
||||
associatedLineMembersForLine.forEach((currentLineMember) => {
|
||||
const foundUserObject = allRelevantUsers?.find((currentUser) =>
|
||||
currentUser._id?.equals(currentLineMember.userId),
|
||||
);
|
||||
|
||||
if (foundUserObject) otherUsers.push(foundUserObject);
|
||||
});
|
||||
|
||||
masterLines.push(
|
||||
new MasterLineData(currentLine, userLineMember, associatedLineMembersForLine, otherUsers),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const resObj = new GetUserLinesResponse(masterLines);
|
||||
|
||||
res.json(new NirvanaResponse<GetUserLinesResponse>(resObj));
|
||||
} catch (error) {
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { JwtClaims, authCheck } from "../middleware/auth";
|
||||
import express, { Application, Request, Response } from "express";
|
||||
|
||||
import { User } from "@nirvana/core/models";
|
||||
import UserSearchResponse from "../../core/responses/userSearch.response";
|
||||
import { UserService } from "../services/user.service";
|
||||
|
||||
export default function getSearchRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// get user details based on id token
|
||||
router.get("/users", authCheck, handleUserSearch);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
async function handleUserSearch(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
const { query } = req.query;
|
||||
|
||||
if (!query) {
|
||||
res.status(400).send("No search query provided!");
|
||||
return;
|
||||
}
|
||||
|
||||
// text search on users
|
||||
const users: User[] | null = await UserService.getUsersLikeEmailAndName(
|
||||
query as string
|
||||
);
|
||||
|
||||
const filteredUsers = users?.filter(
|
||||
(currUser) => currUser._id?.toString() !== userInfo.userId
|
||||
);
|
||||
|
||||
const resObj = new UserSearchResponse(filteredUsers ?? []);
|
||||
|
||||
res.send(resObj);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).send(`something went wrong`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
||||
import { JwtClaims, authCheck } from "../middleware/auth";
|
||||
import express, { Application, Request, Response } from "express";
|
||||
|
||||
import LoginResponse from "../../core/responses/login.response";
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import { ObjectID } from "bson";
|
||||
import { ObjectId } from "mongodb";
|
||||
import UserDetailsResponse from "../../core/responses/userDetails.response";
|
||||
import { UserService } from "../services/user.service";
|
||||
import { UserStatus } from "../../core/models/user.model";
|
||||
import { collections } from "../services/database.service";
|
||||
import { loadConfig } from "../config";
|
||||
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const config = loadConfig();
|
||||
|
||||
const client = new OAuth2Client(config.GOOGLE_AUTH_CLIENT_ID);
|
||||
|
||||
export default function getUserRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// get user details based on id token
|
||||
router.get("/", authCheck, getUserDetails);
|
||||
|
||||
router.get("/login", login);
|
||||
|
||||
router.get("/authcheck", authCheck, handleAuthCheck);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
async function handleAuthCheck(req: Request, res: Response) {
|
||||
try {
|
||||
res.status(200).json("You are good to go!");
|
||||
} catch (error) {
|
||||
res.status(401).json("Unauthorized");
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserDetails(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
const user = await UserService.getUserById(userInfo.userId);
|
||||
|
||||
user
|
||||
? res.status(200).json(new UserDetailsResponse(user))
|
||||
: res.status(404).json("No such user");
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).json(`Problem with signing user up or logging in`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Create user if doesn't exist
|
||||
* Returns jwt token for client and user details
|
||||
*/
|
||||
async function login(req: Request, res: Response) {
|
||||
// passed in accesstoken no matter what
|
||||
const { access_token, id_token } = req.query;
|
||||
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: (id_token as string) ?? "",
|
||||
audience: config.GOOGLE_AUTH_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
});
|
||||
const googleUserId = ticket.getPayload()?.sub as string;
|
||||
const email = ticket.getPayload()?.email as string;
|
||||
|
||||
if (!googleUserId || !email) {
|
||||
res.status(401).json("no google account found");
|
||||
return;
|
||||
}
|
||||
|
||||
// return user details if it passed auth middleware
|
||||
let user = await UserService.getUserByEmail(email);
|
||||
|
||||
// if no user found, then go ahead and create user
|
||||
if (!user) {
|
||||
if (!access_token) {
|
||||
res.status(400).json("No access token provided");
|
||||
return;
|
||||
}
|
||||
|
||||
// get google user info from access token
|
||||
const userInfo: GoogleUserInfo =
|
||||
await UserService.getGoogleUserInfoWithAccessToken(
|
||||
access_token as string
|
||||
);
|
||||
|
||||
// create initial user model object
|
||||
|
||||
const newUser = new User(
|
||||
googleUserId,
|
||||
userInfo.email,
|
||||
userInfo.name,
|
||||
userInfo.given_name,
|
||||
userInfo.family_name,
|
||||
new Date(),
|
||||
userInfo.picture,
|
||||
userInfo.verifiedEmail,
|
||||
userInfo.locale
|
||||
);
|
||||
|
||||
// create user if not exists
|
||||
const insertResult = await UserService.createUserIfNotExists(newUser);
|
||||
|
||||
newUser._id = insertResult?.insertedId;
|
||||
|
||||
// create jwt token with new user info
|
||||
const jwtToken = jwt.sign(
|
||||
{
|
||||
userId: newUser._id,
|
||||
googleUserId: newUser.googleId,
|
||||
picture: newUser.picture,
|
||||
email: newUser.email,
|
||||
name: newUser.name,
|
||||
},
|
||||
config.JWT_TOKEN_SECRET
|
||||
);
|
||||
|
||||
insertResult
|
||||
? res.status(200).json(new LoginResponse(jwtToken, newUser))
|
||||
: res.status(500).json("Failed to create account, already exists");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// create jwt token with new user info
|
||||
const jwtToken = jwt.sign(
|
||||
{
|
||||
userId: user._id,
|
||||
googleUserId: user.googleId,
|
||||
picture: user.picture,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
},
|
||||
config.JWT_TOKEN_SECRET
|
||||
);
|
||||
|
||||
res.status(200).json(new LoginResponse(jwtToken, user));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).json(`Problem with signing user up or logging in`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user