Check browser cookie in AngularJS - 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');
}]);

Related

How to retrieve user profile to the frontend | PassportJs

I'm trying to log in a user using Passport Js (Google Auth), I configured Passport Js and i'm getting the user profile in my console, but I didn't know how to show the user profile in frontend, the configure for PassportJs goes like:
passport.use(
new GoogleStrategy(
{
clientID: "",
clientSecret: "",
callbackURL: "/auth/google/callback",
scope: ["profile", "email"],
},
async (accessToken, refreshToken, profile, done) => {
// find current user in UserModel
const currentUser = await User.findOne({
googleId: profile.id
});
// create new user if the database doesn't have this user
if (!currentUser) {
const newUser = await new User({
googleId: profile.id,
email: profile.emails[0].value,
displayName: profile.displayName,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
profilePic: profile.photos[0].value,
}).save();
if (newUser) {
done(null, newUser);
}
}
console.log("CURRNT USER: ", currentUser);
done(null, currentUser);
}
)
);
// serialize the user.id to save in the cookie session
// so the browser will remember the user when login
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => {
done(null, user);
})
.catch(e => {
done(new Error("Failed to deserialize an user"));
});
});
And in the Auth.js route:
// when login is successful, retrieve user info
router.get("/login/success", (req, res) => {
if (req.user) {
res.status(200).json({
error: false,
message: "succesfull",
user: req.user,
cookies: req.cookies
});
} else {
res.status(403).json({ error: true, message: "Not Authorized" });
}
});
// auth with google
router.get("/google", passport.authenticate("google", ["profile", "email"]))
// redirect to home page after successfully login via google
router.get(
"/auth/google/callback",
passport.authenticate("google", {
successRedirect: "http://localhost:3000/",
failureRedirect: "/login/failed"
})
);
I'm using Context to let the app knows if the user is logged in or not.
**Login.jsx: Normal Logging Using express and Mongodb **
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/login", {
email: userRef.current.value,
password: passwordRef.current.value,
});
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE" });
setError(true)
}
};
//Now I tried this code to log in a user using Google Auth but it didn't work
useEffect(() => {
fetch(`http://localhost:4000/login/success`, {
method: 'GET',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials': true,
},
})
dispatch({ type: "LOGIN_START" })
.then((response) => {
if (response.status === 200) return response.json();
throw new Error('failed to authenticate user');
})
.then((responseJson) => {
dispatch({ type: "LOGIN_SUCCESS", payload: responseJson.data });
})
.catch((error) => {
dispatch({ type: "LOGIN_FAILURE" });
console.error("Failed to authenticate user", error)
});
}, []);
const google = () => {
window.open("http://localhost:4000/auth/google/callback", "_self");
};
The full code is here: https://codesandbox.io/s/nervous-mountain-e5t9d4?file=/api/routes/auth.js
let me share with you the perfect code.
passportStratergy.js
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../model/user');
const { USER_TYPES } = require('../constants/authConstant');
const googlePassportStrategy = passport => {
passport.serializeUser(function (user, cb) {
cb(null, user);
});
passport.deserializeUser(function (user, cb) {
cb(null, user);
});
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENTID,
clientSecret: process.env.GOOGLE_CLIENTSECRET,
callbackURL: process.env.GOOGLE_CALLBACKURL
}, async function (accessToken, refreshToken, profile, done) {
if (profile){
let userObj = {
'username':profile.displayName,
'ssoAuth': { 'googleId': profile.id },
'email': profile.emails !== undefined ? profile.emails[0].value : '',
'password':'',
'userType':USER_TYPES.User
};
let found = await User.findOne(User,{ 'email': userObj.email });
if (found) {
const id = found.id;
await User.updateOne(User, { _id :id }, userObj);
}
else {
await User.create(User, userObj);
}
let user = await User.findOne(User,{ 'ssoAuth.googleId':profile.id });
return done(null, user);
}
return done(null, null);
}
));
};
module.exports = { googlePassportStrategy };
auth.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { socialLogin } = require('../services/auth');
router.get('/auth/google/error', (req, res) => {
res.loginFailed({ message:'Login Failed' });
});
router.get('/auth/google',passport.authenticate('google', {
scope: ['profile', 'email'],
session:false
}));
router.get('/auth/google/callback',
(req,res,next)=>{
passport.authenticate('google', { failureRedirect: '/auth/google/error' }, async (error, user , info) => {
if (error){
return res.send({ message:error.message });
}
if (user){
try {
//let result = await socialLogin(user.email);
// here your business logic for login user.
return res.send({
data: result.data,
message:'Login Successful'
});
} catch (error) {
return res.send({ message: error.message });
}
}
})(req,res,next);
});
module.exports = router;
index.js
const passport = require('passport');
const { googlePassportStrategy } = require('./passportStrategy');
googlePassportStrategy(passport);

PassportJS Express req.user not persisting in Heroku

I am using React and Express. Only the React is hosted on heroku and I am hosting the Express server locally. With Express I am using Passportjs with MongoDB.
The problem is that React clien t works well on local deployment, however once I deploy my React App on Heroku it does not work well propertly. When using my deployed React app, I can register a user but I cannot log in a user. It does not return error and POST("/login") returns "Successfully Authenticated" back to me and when I try to access req.user using axios it returns nothing back when it should be returning the user.
React Code
const getUser = () => {
axios({
method: "GET",
withCredentials: true,
url: "http://localhost:3001/user",
})
.then((res) => {
{
console.log(res.data);
if (res.data.username != null)
setMessage("Welcome " + res.data.username);
}
})
.catch((err) => console.log(err));
};
const loginTheUser = async () => {
await axios({
method: "POST",
data: {
username: username,
password: password,
},
withCredentials: true,
url: "http://localhost:3001/login",
}).then((res) => {
if (res.data === "Successfully Authenticated") {
history.push("/");
}
console.log(res.data);
});
await getUser();
};
Express code
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: [
"http://localhost:3000",
"https://my-herokuapp.com",
], // <-- location of the react app were connecting to
credentials: true,
})
);
app.use(
session({
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//Login
app.post("/login", (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) throw err;
if (!user) {
console.log("Unsuccessful login");
res.send("Unsuccessful login");
} else {
req.logIn(user, (err) => {
if (err) throw err;
{
console.log("Login success");
res.send("Successfully Authenticated");
}
});
}
})(req, res, next);
});
//Register
app.post("/register", (req, res) => {
User.findOne({ username: req.body.username }, async (err, doc) => {
if (err) throw err;
if (doc) res.send("User Already Exists");
if (!doc) {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({
username: req.body.username,
password: hashedPassword,
});
await newUser.save();
res.send("User Created");
}
});
});
//get User
app.get("/user", (req, res) => {
res.send(req.user); // The req.user stores the entire user that has been authenticated inside of it.
});
Passport config
const User = require("./user");
const bcrypt = require("bcryptjs");
const localStrategy = require("passport-local").Strategy;
module.exports = function (passport) {
passport.use(
new localStrategy((username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) throw err;
if (!user) return done(null, false);
bcrypt.compare(password, user.password, (err, result) => {
if (err) throw err;
if (result === true) {
return done(null, user);
} else {
return done(null, false);
}
});
});
})
);
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
User.findOne({ _id: id }, (err, user) => {
const userInformation = {
username: user.username,
};
cb(err, userInformation);
});
});
};

Passport middleware for express js using azuread-openidconnect

I have configured the OIDCStrategy in passport and the app redirect to account login then I get an access token. After I tried to protect a route using like below but it always redirect to the authentication page.
app.get('/test', (req, res, next) => {
if (req.isAuthenticated()) { return next(); }
res.redirect('/auth');
}, (request, response, next) => {
response.status(200)
.json({
message: 'SUCCESS',
});
})
I have also tried this method
app.get('/test', passport.authenticate('azuread-openidconnect', { session: true, failureRedirect: '/auth' }), (request, response, next) => {
response.status(200)
.json({
message: 'SUCCESS',
});
});
Passport configuration
const passport = require('passport');
const { OIDCStrategy, BearerStrategy } = require('passport-azure-ad');
const passportModule = express.Router();
passport.serializeUser(function (user, done) {
done(null, user.oid);
});
passport.deserializeUser(function (oid, done) {
findByOid(oid, function (err, user) {
done(err, user);
});
});
const users = [];
const findByOid = function (oid, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
console.info('we are using user: ', user);
if (user.oid === oid) {
return fn(null, user);
}
}
return fn(null, null);
};
const azureOpenIDStrategy = new OIDCStrategy({
identityMetadata: "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",
clientID: "cec04b71-137b-4a99-80c6-e0fc88a2e7c5",
responseType: "code",
responseMode: 'form_post',
redirectUrl: redirectUrl,
allowHttpForRedirectUrl: false,
clientSecret: "",
isB2C: false,
validateIssuer: false,
issuer: null,
passReqToCallback: false,
useCookieInsteadOfSession: true,
cookieEncryptionKeys: [
{ 'key': '12345678901234567890123456789012', 'iv': '123456789012' },
{ 'key': 'abcdefghijklmnopqrstuvwxyzabcdef', 'iv': 'abcdefghijkl' }
],
scope: ['profile', 'OnlineMeetings.ReadWrite', 'Calendars.ReadWrite', 'People.Read.All'],
loggingLevel: 'info',
nonceLifetime: null,
nonceMaxAmount: 5,
clockSkew: null
}, function (iss, sub, profile, jwtClaims, accessToken, refreshToken, params, done) {
if (!profile.oid) {
return done(new Error("No oid found"), null);
}
console.log(`iss: ${iss}`);
console.log(`sub: ${sub}`);
console.log(`profile: ${JSON.stringify(profile)}`);
console.log(`accessToken: ${accessToken}`);
console.log(`jwtClaims: ${JSON.stringify(jwtClaims)}`);
console.log(`refreshToken: ${refreshToken}`);
console.log(`params: ${params}`);
process.nextTick(function () {
findByOid(profile.oid, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
// "Auto-registration"
users.push(profile);
return done(null, profile);
}
return done(null, user);
});
})
});
passportModule.use(passport.initialize());
passportModule.use(passport.session());
passport.use(azureOpenIDStrategy);
How to protect routes properly using azure open-id connect strategy?
Attach the retrieved token in your request (in the Authorization header with this format: "Bearer {access token}") and Use passport.authenticate to protect routes.

New endpoints not found [Angular Fullstack]

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.

Redirect after email authentication

I'm having trouble redirecting the user after successful login, i've read the documentation for Firebase and tried several things but no luck so far
Can anyone point me into the right direction ?
Thanks in advance,
Jérémie.
Here's the controller.js
.controller('LoginCtrl', function($scope, $ionicPopup, $state, Auth) {
$scope.data = {};
$scope.login = function() {
Auth.login($scope.data.email, $scope.data.password).then(function() {
$state.go("tab-discover");
})
.error(function() {
var alertPopup = $ionicPopup.show({
title: 'Mauvais identifiants',
template: 'Veuillez recommencer'
});
});
}
$scope.signup = function() {
Auth.signup($scope.data.email, $scope.data.password)
.error(function() {
var alertPopup = $ionicPopup.show({
title: 'Erreur',
template: 'Un probleme est survenu'
});
});
}
})
And the services.js
.factory("Auth", function(FURL, $firebaseAuth) {
var ref = new Firebase(FURL);
var auth = $firebaseAuth(ref);
var Auth = {
user: {},
login: function(email, password){
console.log("loginService", email, password);
return ref.authWithPassword({
"email": email,
"password": password
}, function(error, authData) {
if (error) {
console.log("La connexion a echoué!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
})
},
signup: function(email, password){
console.log("signupService", email, password);
return ref.createUser({
"email": email,
"password": password
}, function(error, userData) {
if (error) {
switch (error.code) {
case "EMAIL_TAKEN":
console.log("The new user account cannot be created because the email is already in use.");
break;
case "INVALID_EMAIL":
console.log("The specified email is not a valid email.");
break;
default:
console.log("Error creating user:", error);
}
} else {
console.log("Successfully created user account with uid:", userData.uid);
}
}).then(function(){
return Auth.login(email, password);
})
}
}
return Auth;
})
It looks like firebase is using callbacks where you're trying to return it as a promise with then. A simple fix would be to pass a callback to your login function and call it inside the firebase callback:
login: function(email, password, callback, onError){
console.log("loginService", email, password);
ref.authWithPassword({
"email": email,
"password": password
}, function(error, authData) {
if (error) {
onError(error);
} else {
callback(authData);
}
})
Then call it like this:
Auth.login($scope.data.email, $scope.data.password, function (data) {
console.log("Authenticated successfully with payload:", data);
$state.go("tab-discover");
}, function (error) {
console.log("La connexion a echoué!", error);
});

Resources