Skip to content

Commit

Permalink
Merge pull request #153 from microsoft/refactoring/Issue-148
Browse files Browse the repository at this point in the history
🛠️ Removing Keycloak Dependency
  • Loading branch information
anuragshukla06 authored Jan 10, 2023
2 parents 943c5fc + ab7755a commit 3f1c0ad
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 12 deletions.
5 changes: 4 additions & 1 deletion server/backend/src/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

import dotenv from 'dotenv';
dotenv.config();

import { loadSecrets } from './secrets/Index';
import cors from '@koa/cors';
import Koa from 'koa';
Expand All @@ -15,6 +14,10 @@ import { catchAll, httpRequestLogger, setupDbConnection, mainLogger as logger }
import { createBlobContainers, createLocalFolders, setupBlobStore } from '@karya/common';
import { envGetNumber, envGetString } from '@karya/misc-utils';

// enable this next line in case you are facing issue : "UNABLE_TO_FIND_LOCAL_ISSUER_CERTIFICATE" while registering into application
// process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';


// Setup Koa application
const app = new Koa();

Expand Down
7 changes: 5 additions & 2 deletions server/backend/src/scripts/AuthBootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { BasicModel } from '@karya/common';
import { ServerUser } from '@karya/core';
import { getCreationCode } from '@karya/misc-utils';
import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';
// import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';

/**
* Function to bootstrap authentication. Creates an admin user and outputs a creation code.
Expand All @@ -30,6 +30,9 @@ export async function bootstrapAuth() {
/** Create an admin user */
const workProvider: ServerUser = {
role: 'ADMIN',
role_mappings: {
role_mappings: ['ADMIN']
},
access_code,
full_name: '',
email: '',
Expand All @@ -40,7 +43,7 @@ export async function bootstrapAuth() {
const insertedRecord = await BasicModel.insertRecord('server_user', workProvider);

/**Create role for admin */
await TokenAuthHandler.assignRole(insertedRecord, 'ADMIN');
// await TokenAuthHandler.assignRole(insertedRecord, 'ADMIN');

if (insertedRecord === null) {
throw new Error('Failed to create record');
Expand Down
11 changes: 8 additions & 3 deletions server/backend/src/scripts/ResetDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Promise as BBPromise } from 'bluebird';
import { knex, setupDbConnection, ServerDbFunctions, mainLogger as logger, BasicModel } from '@karya/common';
import { bootstrapAuth } from './AuthBootstrap';
import { createAllMatViews } from '../models/MatViewModel';
import * as KeycloakUtils from '../utils/auth/KeycloakUtils';
// import * as KeycloakUtils from '../utils/auth/KeycloakUtils';

/**
* Function to recreate all tables in the database
Expand Down Expand Up @@ -46,8 +46,13 @@ let scriptSequence = ['recreate-tables', 'auth-bootstrap'];
setupDbConnection();

// Remove server users from keycloak
const allServerUsers = await BasicModel.getRecords('server_user', {});
await KeycloakUtils.removeAllUsers();
// try {
// const allServerUsers = await BasicModel.getRecords('server_user', {});
// await KeycloakUtils.removeAllUsers();
// } catch (e) {
// logger.warn(e)
// }


await BBPromise.mapSeries(scriptSequence, async (action) => {
switch (action) {
Expand Down
12 changes: 10 additions & 2 deletions server/backend/src/user-routes-controllers/ServerUserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { ServerUser } from '@karya/core';
import { getCreationCode } from '@karya/misc-utils';
import { UserRouteMiddleware } from '../routes/UserRoutes';
import * as HttpResponse from '@karya/http-response';
import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';
import RoleMappings from "../utils/auth/tokenAuthoriser/RoleMappings";
// import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';

/**
* Create a new server user. Cannot create an admin through this endpoint.
Expand All @@ -20,6 +21,13 @@ export const create: UserRouteMiddleware = async (ctx) => {
if (server_user.role === 'ADMIN') {
return HttpResponse.BadRequest(ctx, 'Cannot create user with ADMIN role');
}
if (server_user.role === 'WORK_PROVIDER') {
server_user.role_mappings = RoleMappings.WORK_PROVIDER
}
if (server_user.role === 'COORDINATOR'){
server_user.role_mappings = RoleMappings.COORDINATOR

}

// Generate access code and ensure it is not repeated
let access_code: string = '';
Expand All @@ -38,7 +46,7 @@ export const create: UserRouteMiddleware = async (ctx) => {

const record = await BasicModel.insertRecord('server_user', server_user);
// Assign work-provider role
await TokenAuthHandler.assignRole(record, server_user.role!);
// await TokenAuthHandler.assignRole(record, server_user.role!);
HttpResponse.OK(ctx, record);
};

Expand Down
4 changes: 2 additions & 2 deletions server/backend/src/user-routes-controllers/TaskController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { upsertKaryaFile } from '../models/KaryaFileModel';
import { inputProcessorQ, outputGeneratorQ } from '../task-ops/Index';
import { csvToJson } from '../scenarios/Common';
import { Promise as BBPromise } from 'bluebird';
import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';
// import * as TokenAuthHandler from '../utils/auth/tokenAuthoriser/tokenAuthHandler/TokenAuthHandler';

// Task route state for routes dealing with a specific task
type TaskState = { task: TaskRecordType };
Expand Down Expand Up @@ -69,7 +69,7 @@ export const create: UserRouteMiddleware = async (ctx) => {

try {
const insertedRecord = await BasicModel.insertRecord('task', task);
await TokenAuthHandler.grantTaskPermission(user, insertedRecord.id, ['read', 'edit']);
// await TokenAuthHandler.grantTaskPermission(user, insertedRecord.id, ['read', 'edit']);
HttpResponse.OK(ctx, insertedRecord);
} catch (e) {
// Internal server error
Expand Down
4 changes: 2 additions & 2 deletions server/backend/src/utils/auth/tokenAuthoriser/Index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import * as HttpResponse from '@karya/http-response';
const policyParser = new PolicyParser(Policy);

export const tokenAuthoriser: UserRouteMiddleware = async (ctx, next) => {
const resourceTokens = policyParser.getResourceTokens(ctx);
const resourceTokens = policyParser.getResourceTokens(ctx); //reource == api
const serverUser = await BasicModel.getSingle('server_user', { id: ctx.state.entity.id });
const userTokens = await TokenAuthHandler.getTokens(serverUser);
const userTokens = serverUser.role_mappings ? serverUser.role_mappings.role_mappings : [];

const accessAllowed = isAccessAllowed(userTokens, resourceTokens);
if (!accessAllowed) return HttpResponse.Forbidden(ctx, 'User does not have enough permissions, please contact admin');
Expand Down
5 changes: 5 additions & 0 deletions server/backend/src/utils/auth/tokenAuthoriser/RoleMappings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
ADMIN: {role_mappings:['ADMIN']},
WORK_PROVIDER: {role_mappings:['WORK_PROVIDER']},
COORDINATOR: {role_mappings:['COORDINATOR']}
};
1 change: 1 addition & 0 deletions server/core/schema/specs/KaryaDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ const karyaDb: DatabaseSpec<KaryaTableName, KaryaString, KaryaObject> = {
['auth_id', ['string', 64], 'not unique', 'nullable', 'mutable'],
['id_token', ['text'], 'unique', 'nullable', 'mutable'],
['role', ['string', 32, 'ServerRole'], 'not unique', 'not nullable', 'not mutable'],
['role_mappings', ['stringarray'], 'not unique', 'nullable', 'mutable'],
['full_name', ['string', 64], 'not unique', 'nullable', 'mutable'],
['email', ['string', 64], 'not unique', 'nullable', 'mutable'],
],
Expand Down

0 comments on commit 3f1c0ad

Please sign in to comment.