New endpoints not found [Angular Fullstack] - angularjs

I am using the Angular Fullstack to create a web application. I have a good number of custom endpoints created. All seem to work except this new endpoint I just created. I already tried reorganizing my endpoints, no new endpoints will work.
'use strict';
var express = require('express');
var controller = require('./proctoring.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.create);
router.put('/:id', controller.upsert);
router.patch('/:id', controller.patch);
router.delete('/:id', controller.destroy);
// Custom routes
router.get('/activeexams/:id', controller.getAvailableExams);
router.get('/openexams/get', controller.getOpenExams);
router.get('/instructor/:id', controller.getInstructor);
router.get('/testsites/get', controller.getTestSites);
router.get('/courses/get', controller.getCourseList);
router.get('/timerestrictions/:id/:uid/:uuid', controller.getTimeRestrictions);
router.get('/fulldays/:id/:uid', controller.getFullDays);
router.get('/getexam/:id/:uid', controller.findExam); // DOESNT WORK
router.post('/saveexam/', controller.saveExam);
router.get('/locations', controller.getTestSites);
module.exports = router;
Service that hits the endpoints
'use strict';
const angular = require('angular');
/*#ngInject*/
export function proctoringService($resource) {
return $resource('api/proctorings/:controller/:id/:uid/:uuid', {
id: '#_id'
}, {
getAvailableExams: { method: 'GET', params: { controller: 'activeexams' }, isArray: true },
getOpenExams: { method: 'GET', params: { controller: 'openexams', id: 'get' } },
getCourseList: { method: 'GET', params: { controller: 'courses', id: 'get', }, isArray: true, },
getInstructor: { method: 'GET', params: { controller: 'instructor' } },
getTestSites: { method: 'GET', params: { controller: 'testsites', id: 'get' }, isArray: true },
getFullTimes: { method: 'GET', params: { controller: 'timerestrictions' }, isArray: true },
saveExam: { method: 'POST', params: { controller: 'saveexam' } },
getFullDays: { method: 'GET', params: { controller: 'fulldays' }, isArray: true },
getMyActiveExams: { method: 'GET', params: { controller: 'instructor', id: 'activeexams' }, isArray: true, },
findExam: { method: 'GET', params: { controller: 'getexam' } },
});
}
export default angular.module('proctoringApp.proctoring', [])
.factory('proctoring', proctoringService)
.name;
Endpoint Controller:
'use strict';
import jsonpatch from 'fast-json-patch';
import {Proctoring, Exam, User, Testsite} from '../../sqldb';
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if(entity) {
return res.status(statusCode).json(entity);
}
return null;
};
}
function patchUpdates(patches) {
return function(entity) {
try {
// eslint-disable-next-line prefer-reflect
jsonpatch.apply(entity, patches, /*validate*/ true);
} catch(err) {
return Promise.reject(err);
}
return entity.save();
};
}
function removeEntity(res) {
return function(entity) {
if(entity) {
return entity.destroy()
.then(() => {
res.status(204).end();
});
}
};
}
function handleEntityNotFound(res) {
return function(entity) {
if(!entity) {
res.status(404).end();
return null;
}
return entity;
};
}
function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
res.status(statusCode).send(err);
};
}
// Gets a list of Proctorings
export function index(req, res) {
return Proctoring.findAll()
.then(respondWithResult(res))
.catch(handleError(res));
}
// Gets a single Proctoring from the DB
export function show(req, res) {
return Proctoring.find({
where: {
_id: req.params.id
}
})
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Creates a new Proctoring in the DB
export function create(req, res) {
return Proctoring.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
// Upserts the given Proctoring in the DB at the specified ID
export function upsert(req, res) {
if(req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Proctoring.upsert(req.body, {
where: {
_id: req.params.id
}
})
.then(respondWithResult(res))
.catch(handleError(res));
}
// Updates an existing Proctoring in the DB
export function patch(req, res) {
if(req.body._id) {
Reflect.deleteProperty(req.body, '_id');
}
return Proctoring.find({
where: {
_id: req.params.id
}
})
.then(handleEntityNotFound(res))
.then(patchUpdates(req.body))
.then(respondWithResult(res))
.catch(handleError(res));
}
// Deletes a Proctoring from the DB
export function destroy(req, res) {
return Proctoring.find({
where: {
_id: req.params.id
}
})
.then(handleEntityNotFound(res))
.then(removeEntity(res))
.catch(handleError(res));
}
// Creates a new Exam in the DB
export function saveExam(req, res) {
return Exam.create(req.body)
.then(respondWithResult(res, 201))
.catch(handleError(res));
}
export function getAvailableExams(req, res) {
let today = new Date();
today.setDate(today.getDate() + 7);
today = today.toISOString();
// Return tests that start date is less
//than today and end date is greater than today
return Exam.findAll({
where: {
course: req.params.id,
enddate: {
gte: today
}
}
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getOpenExams(req, res) {
let today = new Date().toISOString();
return Exam.findAndCountAll({
where: {
startdate: {
lte: today
},
enddate: {
gte: today
}
}
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getMyActiveExams(req, res) {
let today = new Date().toISOString();
return Exam.findAll({
where: {
uid: req.params.uid,
startdate: {
lte: today
},
enddate: {
gte: today
}
}
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getTestSites(req, res) {
return Testsite.findAll()
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getInstructor(req, res) {
return User.find({
where: {
_id: req.params.id
}
})
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getCourseList(req, res) {
return Exam.findAll({
attributes: ['course'],
group: 'course'
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getFullDays(req, res) {
return Proctoring.findAll({
attributes: ['testdate'],
where: {
lid: req.params.id,
},
group: ['testdate', 'shift'],
having: ['count(*) >= ' + req.params.uid],
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function getTimeRestrictions(req, res) {
let D = new Date(req.params.uuid).toISOString();
// DONE: Get restricted times for given day selected
return Proctoring.findAll({
attributes: ['shift'],
where: {
lid: req.params.id,
testdate: D
},
group: ['shift'],
having: ['count(*) >=' + req.params.uid],
})
.then(respondWithResult(res))
.catch(handleError(res));
}
export function findExam(req, res) {
return Proctoring.find({
where: {
uid: req.params.id,
eid: req.params.uid,
}
})
.then(handleEntityNotFound(res))
.then(respondWithResult(res))
.catch(handleError(res));
}
When I try to access all my other endpoints with either the browser or postman, they return as they should. When I try to add even any new simple endpoints, they are not found.
I don't know if there is some sort of limit as to how many endpoints you can have; there shouldn't be.
Anyone have any ideas? I receive an error 404.

Related

react-query customHook refetchOnWindowFocus

I am creating individual hooks using react-query. Where would I add in refetchOnWindowFocus: false ? as it is not currently being read and the data is being re-fetched when returning to the window.
const useFetchOverview = () => {
return useQuery(["userData", { refetchOnWindowFocus: false }],
async () => {
const { data } = await axios({
url: useFetchOverviewUrl,
headers: { ...getHeaders(reduxState) },
method: "get"
});
return data;
});
};
const { isLoading, data: userOverviewData } = useFetchOverview();
this should be third parameter after fuinction:
return useQuery(["userData"],
async () => {
const { data } = await axios({
url: useFetchOverviewUrl,
headers: { ...getHeaders(reduxState) },
method: "get"
});
return data;
}, { refetchOnWindowFocus: false });
ex: useQuery(queryKey, queryFn?, options)
check this for your reference: https://tanstack.com/query/v4/docs/reference/useQuery?from=reactQueryV3&original=https://react-query-v3.tanstack.com/reference/useQuery
OR you can write it for global:
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
})

Session returns null Get request however in Post returns the session correctly in Next.js in server side (nextAuth)

I am trying to get the session data such as id, name, etc on the server-side but returns null in the terminal.
In the GET Method session is null, however, in POST method returns the session perfectly.
import { getSession } from "next-auth/react";
export default async (req, res) => {
const { method } = req;
switch (method) {
case "GET":
try {
const session = await getSession({ req });
console.log(JSON.stringify(session)); //Returns null
const jobs = await prisma.jobs.findMany();
return res.status(200).json({ success: true, jobs });
} catch (error) {
return res.status(404).json({
success: false,
message: error.message,
});
}
}
case "POST":
try {
const session = await getSession({ req });
console.log(JSON.stringify(session)); // here returns the session
if (!session || session.role != 2) {
return res.status(401).json({
msg: "You are not authorized to perform this action",
});
}
[...nextauth].js
...nextauth.js file applying credentials provider, I am not sure if I have to implement anything else in addition
import NextAuth from "next-auth";
import CredentialProvider from "next-auth/providers/credentials";
import axios from "axios";
export default NextAuth({
providers: [
CredentialProvider({
name: "credentials",
async authorize(credentials) {
try {
const user = await axios.post(
`${process.env.API_URL}/auth/authentication/login`,
{
email: credentials.email,
password: credentials.password,
}
);
if (!user.data.user) {
return null;
}
if (user.data.user) {
return {
id: user.data.user.id,
name: user.data.user.name,
surname: user.data.user.surname,
email: user.data.user.email,
role: user.data.user.role,
};
}
} catch (error) {
console.error(error);
}
},
}),
],
callbacks: {
jwt: ({ token, user }) => {
if (user) {
token.id = user.id;
token.name = user.name;
token.surname = user.surname;
token.email = user.email;
token.role = user.role;
}
return token;
},
session: ({ session, token }) => {
if (token) {
session.id = token.id;
session.name = token.name;
session.surname = token.surname;
session.email = token.email;
session.role = token.role;
}
return session;
},
},
secret: process.env.SECRET_KEY,
jwt: {
secret: process.env.SECRET_KEY,
encryption: true,
maxAge: 5 * 60 * 1000,
},
pages: {
signIn: "/auth/login",
},
});
This is weird. Can you try moving const session = await getSession({ req }) just before the switch statement?
...
const session = await getSession({ req });
console.log(JSON.stringify(session));
switch (method) {
...
}
....

NestJs Authentication Tutorial always returns 401 Unauthorized after implementing local strategy (When using browser)

What I want to do is a simple authentication using passport as this tutorial suggests: https://docs.nestjs.com/techniques/authentication
I followed this tutorial all along and works when i use Insomnia, Swagger or Postman. Later I created my front-end in react but the requests always returns
POST http://localhost:3333/auth/login 401 (Unauthorized)
{statusCode: 401, message: 'Unauthorized'}.
Other routes like /user/getAll work normally in swagger/postman and in the browser. But the auth route auth/login only works in swagger/postman
Am I missing something here?
I looking for a solution for 4 hours and all the solutions that I found did not work in my project.
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const corsOptions = {
origin: '*',
credentials: true,
allowedHeaders: 'Content-Type, Accept, Origin',
preflightContinue: false,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
};
app.enableCors(corsOptions);
app.use(helmet());
app.use(cookieParser());
// app.use(csurf());
const config = new DocumentBuilder()
.setTitle('Nyx Swagger')
.setDescription('The Nyx API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
app.useGlobalPipes(new ValidationPipe());
await app.listen(process.env.PORT || 3333);
}
bootstrap();
app.module.ts
#Module({
imports: [
MongooseModule.forRoot(
'mongodb+srv://USERNAME:PASSWORD#db-beta.6pfkk.mongodb.net/db-beta?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
),
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
AuthModule,
UsersModule,
],
controllers: [AppController],
providers: [
LocalStrategy,
],
})
export class AppModule {}
app.controller.ts
#Controller()
export class AppController {
constructor(private authService: AuthService) {}
#UseGuards(LocalAuthGuard)
#Post('auth/login')
async login(
#Body() _: MakeAuthDto,
#Request() req,
#Res({ passthrough: true }) res,
) {
const access_token = await this.authService.login(req.user, req.ip);
res.cookie('jwt', access_token);
return req.user;
}
}
auth.module.ts
#Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: process.env.JWTSECRET,
signOptions: { expiresIn: '7d' },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
auth.service.ts
#Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
) {}
async validateUser(email: string, pass: string): Promise<UserDocument | any> {
const user = await this.usersService.findOne({ email } as any, true);
if (
user &&
(await user.compareHash(pass)) &&
user.hasAccess &&
!user.deleted
) {
const {
password,
verificationCode,
ips,
deleted,
hasAccess,
usageTerms,
usageTermsHistory,
...result
} = user.toObject();
return result;
}
return null;
}
async login(user: UserDocument, ip: string): Promise<string> {
const payload = {
email: user.email,
sub: user._id,
name: user.name,
roles: user.roles,
};
await this.usersService.updateLastLogin(user._id, ip);
return this.jwtService.sign(payload);
}
}
jwt.strategy.ts
const cookieExtractor = function (req) {
let token = null;
if (req && req.cookies) {
token = req.cookies['jwt'];
}
return token;
};
#Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([cookieExtractor]),
ignoreExpiration: false,
secretOrKey: process.env.JWTSECRET,
});
}
async validate(payload: any) {
return {
_id: payload.sub,
name: payload.name,
email: payload.email,
roles: payload.roles,
};
}
}
local.strategy.ts
#Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string): Promise<UserDocument> {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
front-end request
export const AuthAPI = {
async login(data) {
const response = await fetch(`${API_URL}/auth/login`, {
method: "POST",
headers: { "Content-type": "application/json", accept: "*/*" },
// credentials: "include",
body: JSON.stringify(data),
});
const json = await response.json();
return json;
},
};
Prints:

How to push data in MongoDB's array with mongoose

I have an empty array in MongoDB
And I want to push the Id in it.
router.put(
"/like/:id",
(req, res) => {
User.findOne({ _id: req.user._id }).then(data => {
if (data) {
Post.update(
{ _id: ObjectId(req.params.id) },
{ $push: { likes: req.user._id } }
);
}
});
}
);
This code is not working on how I achieve this.
router.put (
"/addlike/:id",
passport.authenticate("jwt", {
session: false
}),
(req, res) => {
// use try-catch
try {
User.findOne({ _id: req.user._id }).then(data => {
if (data) {
Post.findOneAndUpdate(
{ _id: ObjectId(req.params.id) },
{ $push: { likes: req.user._id },
{ "new": true, "upsert": true} }
);
}
});
} catch(err){
// handle error
console.log('Error => ', err);
}
}
);
I have tested this in my local system ... working fine

Check browser cookie in AngularJS

I set cookie by hapi-auth-cookie. Can i check in AngularJS is cookie exists?
data.js
server.register(Cookie, function(err) {
if(err) {
console.error(err);
throw err;
}
server.auth.strategy('session', 'cookie', {
password: 'fuckthebritisharmytooralooralooraloo',
isSecure: false,
cookie: 'session',
ttl: 24*60*60*1000
});
server.route({
method: 'POST',
path: '/login',
config: {
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
handler: function(req, res) {
if (req.auth.isAuthenticated) {
console.info('Already!');
req.cookieAuth.clear(); // Delete
return res.redirect('/');
}
var username = req.payload.username;
db.get('user_' + req.payload.username).then(function(data) {
var user = data;
var pass = data.password;
if(!user) {
return console.error('Can`t find user!');
}
var password = req.payload.password;
return Bcrypt.compare(password, pass, function(err, isValid) {
if(isValid) {
req.server.log('Boom, okay!');
req.cookieAuth.set(user);
return res.redirect('/');
}
return res.redirect('/login');
})
})
.catch((err) => {
if (err) {
console.error(err);
throw err;
}
});
}
}
});
});
You can access like this if you are using Angularjs 1.4 and above
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
$scope.session = $cookies.get('session');
}]);

Resources