Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwas1 committed Nov 24, 2023
2 parents 030949c + e6fb468 commit a0aad2e
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 154 deletions.
22 changes: 22 additions & 0 deletions server/.env.sample
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
PORT=9000
HOST=localhost
LOG_FILEPATH=../log/studio-server.log
LOG_DIR=./log
LOG_TIMESTAMP_FORMAT=YYYY-MM-DD HH:mm:ss.SSS
LOG_LEVEL=debug
DATABASE_FILEPATH=../db/studio-server.db
DID_METHOD_NAME=hs
JWT_SECRET= 00c2c433-a077-4e68-b19c-1234f014a510
STUDIO_SERVER_BASE_URL=http://localhost:9000/
NODE_SERVER_BASE_URL=http://localhost:5000/
NODE_SERVER_DID_CREATE_EP=api/did/create_tmp
NODE_SERVER_SCHEMA_CREATE_EP=api/schema/create
DB_URL=
PATH_TO_ISSUE_CRED=api/v1/credential/walletAccepct
SSE_CLIENT_URL=http://localhost:9001
WHITELISTED_CORS = ["http://localhost:9000","http://localhost:9001","http://192.168.29.12:9001", "https://localhost:9001", "http://192.168.29.209:9001", "http://entity.hypersign.id","https://entity.hypersign.id","http://localhost:9001", "https://wallet-stage.hypersign.id", "http://localhost:4999","192.168.29.13",'http://localhost:1234','http://localhost:4000',"https://wallet-jagrat.hypersign.id" '*']
EMAIL_CREDENTITAL_SCHEMA_ID=sch:hid:testnet:zufjU7LuQuJNFiUpuhCwYkTrakUu1VmtxE9SPi5TwfUB:1.0

# Hid-node related
HID_NETWORK_RPC= https://rpc.jagrat.hypersign.id/
HID_NETWORK_API= https://api.jagrat.hypersign.id/
68 changes: 0 additions & 68 deletions server/hypersign.json

This file was deleted.

2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.14.2",
"hid-hd-wallet": "git+https://github.com/hypersign-protocol/hid-hd-wallet.git#ssi-integration",
"hid-hd-wallet": "git+https://github.com/hypersign-protocol/hid-hd-wallet.git#main",
"hs-ssi-sdk": "^7.0.1",
"hypersign-auth-node-sdk": "^6.4.5",
"jsonwebtoken": "^8.5.1",
Expand Down
19 changes: 17 additions & 2 deletions server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const HIDWallet = require('hid-hd-wallet');
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import { walletAuthRoutes } from './routes/walletAuth';
import { port, logger, walletOptions, mnemonic } from './config';
import { port, logger, walletOptions, mnemonic, schemaId, studioServerBaseUrl, jwtSecret, jwtExpiryInMilli } from './config';
import authRoutes from './routes/auth';
import blogRoutes from './routes/blog';
import appRoutes from './routes/app';
Expand All @@ -31,10 +31,25 @@ export default function app() {
const server = http.createServer(app);

const hidWalletInstance = new HIDWallet(walletOptions);
const hypersignAuthOptions = {
serviceName: 'Entity Studio Dashboard',
serviceEp: studioServerBaseUrl,
schemaId,
accessToken: {
secret: jwtSecret,
expiryTime: jwtExpiryInMilli,
},
refreshToken: {
secret: jwtSecret,
expiryTime: jwtExpiryInMilli,
},
networkUrl: walletOptions.hidNodeRPCUrl,
networkRestUrl: walletOptions.hidNodeRestUrl
}
hidWalletInstance
.generateWallet({ mnemonic })
.then(async () => {
hypersign = new HypersignAuth(server, hidWalletInstance.offlineSigner);
hypersign = new HypersignAuth(server, hidWalletInstance.offlineSigner, hypersignAuthOptions);
await hypersign.init();
app.use(express.static('public'));

Expand Down
28 changes: 9 additions & 19 deletions server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ logger.setLevel(process.env.LOG_LEVEL || 'info');

const port = process.env.PORT || 5000;
const host = process.env.HOST || 'localhost';
const WALLET_WEBHOOK = process.env.WALLET_WEB_HOOK;
const WALLET_WEB_HOOK_ORG_DID = process.env.WALLET_WEB_HOOK_ORG_DID;
const WALLET_WEB_HOOK_CREAD = process.env.WALLET_WEB_HOOK_CREAD;
const ORG_SERVICE_ENDPOINT_GET_STATUS = process.env.ORG_SERVICE_END_POINT;
const WALLET_WEBHOOK = `${process.env.STUDIO_SERVER_BASE_URL}api/v1/schema/status`;
const WALLET_WEB_HOOK_ORG_DID = `${process.env.STUDIO_SERVER_BASE_URL}api/v1/org/status`;
const WALLET_WEB_HOOK_CREAD = `${process.env.STUDIO_SERVER_BASE_URL}api/v1/credential/status`;
const ORG_SERVICE_ENDPOINT_GET_STATUS = `${process.env.STUDIO_SERVER_BASE_URL}api/v1/org`;
const bootstrapConfig = {
keysfilePath: path.join(__dirname + '/keys.json'),
schemafilePath: path.join(__dirname + '/schema.json'),
Expand All @@ -53,9 +53,7 @@ const did = {
};
const studioServerBaseUrl = process.env.STUDIO_SERVER_BASE_URL;
//Secrets
const rawData = fs.readFileSync('hypersign.json');
const hypersignjsondata = JSON.parse(rawData.toString());
const jwtSecret = process.env.JWT_SECRET || hypersignjsondata.jwt.secret || 'secretKey';
const jwtSecret = process.env.JWT_SECRET || 'secretKey';
const jwtExpiryInMilli = 240000;

const nodeServer = {
Expand All @@ -69,14 +67,6 @@ const dbConnUrl =
? process.env.DB_URL
: 'mongodb://admin:[email protected]:27017,cluster0-shard-00-01.jg0ef.mongodb.net:27017,cluster0-shard-00-02.jg0ef.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-n72avn-shard-0&authSource=admin&retryWrites=true&w=majority';
// DID Related:
const mail = {
host: process.env.MAIL_HOST || 'smtp.gmail.com',
port: process.env.MAIL_PORT || 465,
user: process.env.MAIL_USERNAME || '[email protected]',
pass: process.env.MAIL_PASSWORD || 'ExamplePassword1@',
name: process.env.MAIL_NAME || 'Hypermine Admin',
};

const options = { nodeUrl: `${nodeServer.baseURl}`, didScheme: 'did:hs' };
const hypersignSDK = {
did: hsdk.did(options),
Expand All @@ -86,14 +76,14 @@ const hypersignSDK = {
const mnemonic =
'retreat seek south invite fall eager engage endorse inquiry sample salad evidence express actor hidden fence anchor crowd two now convince convince park bag';
const walletOptions = {
hidNodeRPCUrl: 'https://rpc.jagrat.hypersign.id/',
hidNodeRestUrl: 'https://api.jagrat.hypersign.id/',
hidNodeRPCUrl: process.env.HID_NETWORK_RPC || 'https://rpc.jagrat.hypersign.id/',
hidNodeRestUrl: process.env.HID_NETWORK_API || 'https://api.jagrat.hypersign.id/',
};
const pathToIssueCred = process.env.PATH_TO_ISSUE_CRED;
const whitelistedCors = process.env.WHITELISTED_CORS || ['*'];
const schemaResolver =
process.env.RPC_ENDPOINT || 'https://api.jagrat.hypersign.id/hypersign-protocol/hidnode/ssi/schema/';

const schemaId = process.env.EMAIL_CREDENTITAL_SCHEMA_ID || "sch:hid:testnet:zufjU7LuQuJNFiUpuhCwYkTrakUu1VmtxE9SPi5TwfUB:1.0"
export {
port,
host,
Expand All @@ -103,7 +93,6 @@ export {
jwtSecret,
jwtExpiryInMilli,
nodeServer,
mail,
bootstrapConfig,
hypersignSDK,
dbConnUrl,
Expand All @@ -118,4 +107,5 @@ export {
sse_client,
whitelistedCors,
schemaResolver,
schemaId
};
65 changes: 2 additions & 63 deletions server/src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { Request, Response } from 'express';
import { User } from '../services/user.service';
import IUser from '../models/IUser';
import { logger, jwtSecret, jwtExpiryInMilli, mail, port, host } from '../config';
import { logger, jwtSecret, jwtExpiryInMilli } from '../config';
import jwt from 'jsonwebtoken';
import { hypersignSDK } from '../config';
import { retrive, store } from '../utils/file';
import { store } from '../utils/file';
import path from 'path';
import fs from 'fs';
import regMailTemplate from '../mailTemplates/registration';
import { MailService } from '../services/mail.service';

const check = (req: Request, res: Response) => {
const param = {
Expand All @@ -25,63 +22,6 @@ const check = (req: Request, res: Response) => {
query = query.slice(0, query.length - 1);
res.redirect(`http://localhost:8080/login${query}`);
};

const register_old = async (req: Request, res: Response) => {
try {
logger.debug(req.body);
const body: IUser = req.body;
const user = new User({ ...body });
// if(user.publicKey == "") throw new Error("PublicKey field can not be null")
const userindbstr = await user.fetch();
if (userindbstr) throw new Error(`User ${user.publicKey} already exists`);
const createdU = await user.create();
res.status(200).send({ status: 200, message: createdU, error: null });
} catch (e) {
res.status(500).send({ status: 500, message: null, error: e });
}
};

const register = async (req: Request, res: Response) => {
try {
logger.debug(req.body);
const body: IUser = req.body;
const user = new User({ ...body });
const userindbstr = await user.fetch({
email: user.email,
publicKey: user.publicKey,
});
if (userindbstr) throw new Error(`User ${user.email} already exists. Please login with Hypersign Credential`);

// will use the publicKey field for storing did
// Generate Verifiable credential for this
const createdU = await user.create();
const userData = JSON.parse(createdU);
jwt.sign(userData, jwtSecret, { expiresIn: jwtExpiryInMilli }, async (err, token) => {
if (err) throw new Error(err);
const link = `http://${host}:${port}/api/auth/credential?token=${token}`;
const mailService = new MailService({ ...mail });
let mailTemplate = regMailTemplate;
mailTemplate = mailTemplate.replace('@@RECEIVERNAME@@', user.fname);
mailTemplate = mailTemplate.replace('@@LINK@@', link);
try {
//TODO: Send email
logger.debug('Before sending the mail');
const info = await mailService.sendEmail(user.email, mailTemplate, 'Account Registration | Hypersign Studio');
logger.debug('Mail is sent ' + info.messageId);
res.status(200).send({
status: 200,
message: info,
error: null,
});
} catch (e) {
throw new Error(`Could not send email to ${user.email}. Please check the email address properly.`);
}
});
} catch (e) {
res.status(500).send({ status: 500, message: null, error: e });
}
};

const getCredential = (req, res) => {
try {
const token = req.query.token;
Expand Down Expand Up @@ -207,7 +147,6 @@ const getNewChallenge = (req: Request, res: Response) => {

export default {
check,
register,
login,
recover,
getNewChallenge,
Expand Down
1 change: 0 additions & 1 deletion server/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { retrive } from '../utils/file';
const filePath = path.join(__dirname + '/../' + 'keys.json');
const router = Router();
router.get('/', authCtrl.check);
router.post('/register', authCtrl.register);
router.post('/login', authCtrl.login);
router.post('/login_pki', verifyAuth, authCtrl.login);
router.post('/recover', authCtrl.recover);
Expand Down

0 comments on commit a0aad2e

Please sign in to comment.