feat(server): added in service script to run a crud
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
import {OpenAPIHono} from "@hono/zod-openapi";
|
||||
|
||||
import {authMiddleware} from "./middleware/authMiddleware.js";
|
||||
import login from "./routes/login.js";
|
||||
import register from "./routes/register.js";
|
||||
import session from "./routes/session.js";
|
||||
import getAccess from "./routes/getUserRoles.js";
|
||||
import {authMiddleware} from "./middleware/authMiddleware.js";
|
||||
import getAccess from "./routes/userRoles/getUserRoles.js";
|
||||
import setAccess from "./routes/userRoles/setUserRoles.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
app.route("auth/login", login);
|
||||
@@ -13,6 +13,10 @@ app.route("auth/session", session);
|
||||
|
||||
// required to login
|
||||
app.use("auth/getuseraccess", authMiddleware);
|
||||
|
||||
app.route("/auth/getuseraccess", getAccess);
|
||||
|
||||
app.use("auth/setuseraccess", authMiddleware);
|
||||
app.route("/auth/setuseraccess", setAccess);
|
||||
|
||||
export default app;
|
||||
|
||||
@@ -3,7 +3,7 @@ import {db} from "../../../../database/dbclient.js";
|
||||
import {users} from "../../../../database/schema/users.js";
|
||||
import {eq, sql} from "drizzle-orm";
|
||||
import {checkPassword} from "../utils/checkPassword.js";
|
||||
import {roleCheck} from "./getUserAccess.js";
|
||||
import {roleCheck} from "./userRoles/getUserAccess.js";
|
||||
|
||||
/**
|
||||
* Authenticate a user and return a JWT.
|
||||
|
||||
@@ -4,10 +4,13 @@ in the login route we attach it to user under roles.
|
||||
*/
|
||||
|
||||
import {eq} from "drizzle-orm";
|
||||
import {db} from "../../../../database/dbclient.js";
|
||||
import {userRoles} from "../../../../database/schema/userRoles.js";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {userRoles} from "../../../../../database/schema/userRoles.js";
|
||||
|
||||
export const roleCheck = async (user_id: any) => {
|
||||
export const roleCheck = async (user_id: string | undefined) => {
|
||||
if (!user_id) {
|
||||
throw Error("Missing user_id");
|
||||
}
|
||||
// get the user roles by the user_id
|
||||
const roles = await db.select().from(userRoles).where(eq(userRoles.user_id, user_id));
|
||||
|
||||
35
server/services/auth/controllers/userRoles/setSysAdmin.ts
Normal file
35
server/services/auth/controllers/userRoles/setSysAdmin.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import {users} from "../../../../../database/schema/users.js";
|
||||
import {eq} from "drizzle-orm";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {userRoles} from "../../../../../database/schema/userRoles.js";
|
||||
import {modules} from "../../../../../database/schema/modules.js";
|
||||
import {roles} from "../../../../../database/schema/roles.js";
|
||||
|
||||
export const setSysAdmin = async (user: any, roleName: any): Promise<void> => {
|
||||
// remove all userRoles to prevent errors
|
||||
try {
|
||||
const remove = await db.delete(userRoles).where(eq(userRoles.user_id, user[0].user_id));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
// now we want to add the user to the system admin.
|
||||
const module = await db.select().from(modules);
|
||||
const role = await db.select().from(roles).where(eq(roles.name, roleName));
|
||||
|
||||
for (let i = 0; i < module.length; i++) {
|
||||
try {
|
||||
const userRole = await db.insert(userRoles).values({
|
||||
user_id: user[0].user_id,
|
||||
role_id: role[0].role_id,
|
||||
module_id: module[i].module_id,
|
||||
role: roleName,
|
||||
});
|
||||
console.log(`${user[0].username} has been granted access to ${module[i].name} with the role ${roleName}`);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
57
server/services/auth/controllers/userRoles/setUserRoles.ts
Normal file
57
server/services/auth/controllers/userRoles/setUserRoles.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
pass over a users uuid and return all modules they have permission too.
|
||||
in the login route we attach it to user under roles.
|
||||
*/
|
||||
|
||||
import {eq} from "drizzle-orm";
|
||||
import {db} from "../../../../../database/dbclient.js";
|
||||
import {userRoles} from "../../../../../database/schema/userRoles.js";
|
||||
import {users} from "../../../../../database/schema/users.js";
|
||||
import {modules} from "../../../../../database/schema/modules.js";
|
||||
import {roles} from "../../../../../database/schema/roles.js";
|
||||
import {setSysAdmin} from "./setSysAdmin.js";
|
||||
|
||||
export const setUserAccess = async (username: string, moduleName: string, roleName: string, override?: string) => {
|
||||
// get the user roles by the user_id
|
||||
const user = await db.select().from(users).where(eq(users.username, username));
|
||||
const module = await db.select().from(modules).where(eq(modules.name, moduleName));
|
||||
|
||||
if (process.env.SECRETOVERRIDECODE != override && roleName === "systemAdmin") {
|
||||
return {success: false, message: "The override code provided is invalid."};
|
||||
}
|
||||
|
||||
const role = await db.select().from(roles).where(eq(roles.name, roleName));
|
||||
|
||||
/**
|
||||
* For system admin we want to do a little more
|
||||
*/
|
||||
|
||||
if (roleName === "systemAdmin") {
|
||||
await setSysAdmin(user, roleName);
|
||||
return {
|
||||
success: true,
|
||||
message: `${username} has been granted access to ${moduleName} with the role ${roleName}`,
|
||||
};
|
||||
}
|
||||
//console.log(user, module, role);
|
||||
|
||||
// set the user
|
||||
try {
|
||||
const userRole = await db
|
||||
.insert(userRoles)
|
||||
.values({user_id: user[0].user_id, role_id: role[0].role_id, module_id: module[0].module_id, role: roleName});
|
||||
//.returning({user: users.username, email: users.email});
|
||||
|
||||
// return c.json({message: "User Registered", user}, 200);
|
||||
return {
|
||||
success: true,
|
||||
message: `${username} has been granted access to ${moduleName} with the role ${roleName}`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `There was an error granting ${username} access to ${moduleName} with the role ${roleName}`,
|
||||
data: error,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {apiHit} from "../../../globalUtils/apiHits.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const responseSchema = z.object({
|
||||
message: z.string().optional().openapi({example: "User Created"}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["Auth"],
|
||||
summary: "Returns the useraccess table",
|
||||
method: "get",
|
||||
path: "/",
|
||||
|
||||
responses: {
|
||||
200: {
|
||||
content: {"application/json": {schema: responseSchema}},
|
||||
description: "Retrieve the user",
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
// apit hit
|
||||
apiHit(c, {endpoint: "api/auth/register"});
|
||||
return c.json({message: "UserRoles coming over"});
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
52
server/services/auth/routes/userRoles/getUserRoles.ts
Normal file
52
server/services/auth/routes/userRoles/getUserRoles.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {z, createRoute, OpenAPIHono} from "@hono/zod-openapi";
|
||||
import {apiHit} from "../../../../globalUtils/apiHits.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import {roleCheck} from "../../controllers/userRoles/getUserAccess.js";
|
||||
import type {CustomJwtPayload} from "../../../../types/jwtToken.js";
|
||||
|
||||
const {verify} = jwt;
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const responseSchema = z.object({
|
||||
message: z.string().optional().openapi({example: "User Created"}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["Auth"],
|
||||
summary: "Returns the useraccess table",
|
||||
method: "get",
|
||||
path: "/",
|
||||
|
||||
responses: {
|
||||
200: {
|
||||
content: {"application/json": {schema: responseSchema}},
|
||||
description: "Retrieve the user",
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
// apit hit
|
||||
apiHit(c, {endpoint: "api/auth/getUserRoles"});
|
||||
const authHeader = c.req.header("Authorization");
|
||||
const token = authHeader?.split("Bearer ")[1] || "";
|
||||
try {
|
||||
const secret = process.env.JWT_SECRET!;
|
||||
if (!secret) {
|
||||
throw new Error("JWT_SECRET is not defined in environment variables");
|
||||
}
|
||||
|
||||
const payload = verify(token, secret) as CustomJwtPayload;
|
||||
|
||||
const canAccess = await roleCheck(payload.user?.user_id);
|
||||
|
||||
return c.json({sucess: true, message: `User ${payload.user?.username} can access`, data: canAccess}, 200);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
return c.json({message: "UserRoles coming over"});
|
||||
}
|
||||
);
|
||||
|
||||
export default app;
|
||||
63
server/services/auth/routes/userRoles/setUserRoles.ts
Normal file
63
server/services/auth/routes/userRoles/setUserRoles.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {createRoute, OpenAPIHono, z} from "@hono/zod-openapi";
|
||||
import {setUserAccess} from "../../controllers/userRoles/setUserRoles.js";
|
||||
import {apiHit} from "../../../../globalUtils/apiHits.js";
|
||||
import {apiReturn} from "../../../../globalUtils/apiReturn.js";
|
||||
|
||||
const app = new OpenAPIHono();
|
||||
|
||||
const responseSchema = z.object({
|
||||
success: z.boolean().openapi({example: true}),
|
||||
message: z.string().optional().openapi({example: "user access"}),
|
||||
data: z.array(z.object({})).optional().openapi({example: []}),
|
||||
});
|
||||
|
||||
const UserAccess = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.regex(/^[a-zA-Z0-9_]{3,30}$/)
|
||||
.openapi({example: "smith034"}),
|
||||
module: z.string().openapi({example: "production"}),
|
||||
role: z.string().openapi({example: "viewer"}),
|
||||
override: z.string().optional().openapi({example: "secretString"}),
|
||||
});
|
||||
|
||||
app.openapi(
|
||||
createRoute({
|
||||
tags: ["Auth"],
|
||||
summary: "Sets Users access",
|
||||
method: "post",
|
||||
path: "/",
|
||||
description: "When logged in you will be able to grant new permissions",
|
||||
request: {
|
||||
body: {
|
||||
content: {
|
||||
"application/json": {schema: UserAccess},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: {
|
||||
content: {"application/json": {schema: responseSchema}},
|
||||
description: "Retrieve the user",
|
||||
},
|
||||
400: {
|
||||
content: {"application/json": {schema: responseSchema}},
|
||||
description: "Failed to get user access",
|
||||
},
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
apiHit(c, {endpoint: "api/auth/setUserRoles"});
|
||||
const {username, module, role, override} = await c.req.json();
|
||||
try {
|
||||
const access = await setUserAccess(username, module, role, override);
|
||||
//return apiReturn(c, true, access?.message, access?.data, 200);
|
||||
return c.json({success: access.success, message: access.message, data: access.data}, 200);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
//return apiReturn(c, false, "Error in setting the user access", error, 400);
|
||||
return c.json({success: false, message: "Error in setting the user access", data: error}, 400);
|
||||
}
|
||||
}
|
||||
);
|
||||
export default app;
|
||||
Reference in New Issue
Block a user