Skip to content

Commit

Permalink
added auth.js for token
Browse files Browse the repository at this point in the history
  • Loading branch information
shaunlumbcgov committed Aug 9, 2023
1 parent 3ad96a5 commit 32cd8b2
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 104 deletions.
79 changes: 9 additions & 70 deletions backend/src/routes/institute-router.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@

const express = require('express');
const express = require("express");
const router = express.Router();
const log = require('../components/logger');
const config = require('../config/index');
const log = require("../components/logger");
const config = require("../config/index");
const NodeCache = require("node-cache");
const jsonwebtoken = require("jsonwebtoken");
const axios = require("axios");
const { checkToken } = require("../components/auth"); // Updated import statement

const cache = new NodeCache({ stdTTL: config.get("server:instituteAPITokenExpiry") });
const listCache = new NodeCache({ stdTTL: 21600 });
const clientId = config.get("oidc:clientId");
const clientSecret = config.get("oidc:clientSecret")
const tokenEndpoint = config.get("oidc:tokenEndpoint")

const data = {
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
};

//Batch Routes
router.get('/school/list', checkToken, getSchoolList);
router.get('/*',checkToken, getInstituteAPI);
router.get('/*', checkToken, getInstituteAPI);

function createSchoolList(schools) {
return schools.map(function(school) {
Expand All @@ -37,11 +27,11 @@ function createSchoolList(schools) {
}

async function getSchoolList(req, res) {
const memToken = await cache.get("token");

if(await !listCache.has("schoollist")){
const url = `${config.get('server:instituteAPIURL')}/institute/school`; // Update the URL according to your API endpoint
axios
.get(url, { headers: { Authorization: `Bearer ${memToken}` } })
.get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } })
.then((response) => {
const schoolList = createSchoolList(response.data)
res.json(schoolList);
Expand All @@ -58,64 +48,13 @@ async function getSchoolList(req, res) {

}

async function getNewToken(req, res, next) {
await axios
.post(tokenEndpoint, data, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((response) => {
let accessToken = response.data.access_token;
cache.set("token", accessToken);
})
.catch((error) => {
console.error("Error:", error.response.data);
});
}
async function checkToken(req, res, next) {
try{
if(await !cache.has("token") ){
await getNewToken();
}
next();
}catch(error){
console.log(error)
}
// }

// async function getInstituteAPI(req, res) {
// console.log("XXX")
// console.log(req)
// console.log("YYY")
// let params = {params: req.query};
// const memToken = await cache.get("token");
// const url = `${config.get('server:instituteAPIURL')}/institute` + req.url;

// params.headers = { Authorization: `Bearer ${memToken}` }
// params.params = req.query
// console.log("PARAMS")
// console.log(params)
// console.log("PARAMZ")
// axios
// .get(url, params)
// .then((response) => {
// res.json(response.data);
// log.info(req.url);
// })
// .catch((e) => {

// log.error('getData Error', e.response ? e.response.status : e.message);
// });
// }


async function getInstituteAPI(req, res) {
console.log(req.query)
const memToken = await cache.get("token");
const url = `${config.get('server:instituteAPIURL')}/institute` + req.url;
axios
.get(url, { headers: { Authorization: `Bearer ${memToken}` } })
.get(url, { headers: { Authorization: `Bearer ${req.accessToken}` } })
.then((response) => {
res.json(response.data);
log.info(req.url);
Expand All @@ -124,4 +63,4 @@ async function getInstituteAPI(req, res) {
log.error('getData Error', e.response ? e.response.status : e.message);
});
}
module.exports = router;
module.exports = router;
3 changes: 2 additions & 1 deletion frontend/src/Services/InstituteService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export default {
return ApiService.apiAxios.get('/api/v1/institute/grade-codes');
},
searchSchools(req: any): Promise<AxiosResponse> {
return ApiService.apiAxios.get('/api/v1/institute/school/paginated?pageSize=3000&searchCriteriaList=' + req.searchCriteriaList);
console.log(req.searchCriteriaList)
return ApiService.apiAxios.get('/api/v1/institute/school/paginated?pageSize=10&searchCriteriaList=' + req.searchCriteriaList);
},

}
69 changes: 36 additions & 33 deletions frontend/src/views/SchoolSearchView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
item-title="label"
item-value="schoolCategoryCode"
label="Jurisdiction"
multiple
></v-select>
</v-col>
<v-col cols="12" md="4">
Expand All @@ -20,6 +21,7 @@
item-value="facilityTypeCode"
:items="types"
label="Types"
multiple
></v-select>
</v-col>
<v-col cols="12">
Expand All @@ -29,15 +31,14 @@
</v-row>

<!-- Search Results Table -->
TOTAL: {{ filteredSchools.totalElements }}
{{ filteredSchools }}
TOTAL: {{ results }}

<!-- <v-data-table
<v-data-table
:headers="headers"
:items="filteredSchools"
item-value="name"
class="elevation-1"
></v-data-table> -->
></v-data-table>
</v-container>
</template>

Expand Down Expand Up @@ -107,39 +108,41 @@ const search = ref('')
const searchSchools = async () => {
// Filter schools based on selected filters
console.log('SEARCH')
const req = {
schoolCategoryCode: selectedJurisdiction.value,
city: selectedCity.value,
facilityTypeCode: selectedType.value,
grade: selectedGrade.value
}
const schoolSearchParam = {
params: {
pageNumber: 1,
pageSize: 10,
searchCriteriaList: JSON.stringify([
{
condition: null,
searchCriteriaList: [
{
key: 'schoolCategoryCode',
operation: 'IN',
value: 'EAR_LEARN,PUBLIC',
valueType: 'String',
condition: 'AND'
}
]
}
])
const params = [
{
condition: null,
searchCriteriaList: []
}
]
if (selectedJurisdiction.value) {
params[0].searchCriteriaList.push({
key: 'schoolCategoryCode',
operation: selectedJurisdiction.value.length > 1 ? 'in' : 'eq',
value: selectedJurisdiction.value.join(', '),
valueType: 'STRING',
condition: 'OR'
})
}
if (selectedType.value) {
params[0].searchCriteriaList.push({
key: 'facilityTypeCode',
operation: 'in',
value: selectedType.value.join(', '),
valueType: 'STRING',
condition: 'AND'
})
}
const searchresults = await InstituteService.searchSchools(schoolSearchParam)
console.log(searchresults.data)
results.value = searchresults.data.totalElements
const jsonString = JSON.stringify(params)
const encodedParams = encodeURIComponent(jsonString)
const req = {
pageNumber: 1,
pageSize: 10,
searchCriteriaList: encodedParams
}
const searchresults = await InstituteService.searchSchools(req)
filteredSchools.value = searchresults.data.content
results.value = searchresults.data.totalElements
}
const resetFilters = () => {
Expand Down

0 comments on commit 32cd8b2

Please sign in to comment.