Redirect after email authentication - angularjs

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);
});

Related

What is the best way to use Google 0Auth

I'm trying to use Google OAuth in my App, on the Log In page and the Sign Up page, I'm looking for the best way and the easiest! I tried Passport Js, but I'm stuck right now.
I'm using Mongoose right now and I'm signing up and in users perfectly, but now i want to add a feature where the user can sign in using his google account, I'm looking for a way where the app can get the Email the user is using for his google account and then look if the email is already registered if so redirect him to the home page and if not sign his email up, save it to database, and then redirect to the home page.
This is how my Auth.js looks like
//REGISTER
router.post("/register", async (req, res) => {
try {
//generate new password
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);
//create new user
const newUser = new User ({
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: hashedPass,
repeatPassword: hashedPass,
birthday: req.body.birthday,
});
//save user and respond
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
//LOGIN
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
// if(!user) return res.status(400).json("Wrong credentials!");
!user && res.status(400).json("Wrong credentials!");
const validated = await bcrypt.compare(req.body.password, user.password);
// if(!validated) return res.status(400).json("Wrong credentials!");
!validated && res.status(400).json("Wrong credentials!");
const { password, ...others } = user._doc;
return res.status(200).json(others);
} catch (err) {
return res.status(500).json(err);
}
});
PassportJs configuration I used: but didn't work
passport.use(
new GoogleStrategy(
{
clientID: "MyClientId",
clientSecret: "Myclientsecret",
callbackURL: "/api/auth/google/callback",
},
function (accessToken, refreshToken, profile, done) {
User.find(
{
social: profile.provider,
social_id: profile.id,
},
(err, user) => {
if (user.length === 0) {
const user = new User({
email: profile.email,
username: profile.displayName,
profilePic: profile.photos[0],
social: profile.provider,
social_id: profile.id,
});
const userModel = new User(data);
userModel.save();
done(null, profile);
}
if (err) {
return done(err);
}
},
);
return done(null, profile);
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
router.get("/login/success", (req, res) => {
if (req.user) {
res.status(200).json({
success: true,
message: "successfull",
user: req.user,
// cookies: req.cookies
});
}
});
router.get("/login/failed", (req, res) => {
res.status(401).json({
success: false,
message: "failure",
});
});
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
router.get(
"/google/callback",
passport.authenticate("google", {
successRedirect: CLIENT_URL,
failureRedirect: "/login/failed",
})
);

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.

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');
}]);

create password and access with password only

Trying to make an admin panel where the admin user can create passwords for the access page. You'll need the password to access the login/register page. I've been trying to make this with json web tokens. I've used the MEAN-stack for this:
access Schema
var accessSchema = new mongoose.Schema({
password: String
});
create jwt
function createAccessToken(password) {
var payload = {
sub: password._id,
iat: moment().unix(),
exp: moment().add(7, 'days').unix()
};
return jwt.encode(payload, config.ACCESSCODE_TOKEN_SECRET);
}
Login and signup
app.post('/auth/loginaccess', function (req, res) {
Access.findOne({ password: req.body.password }, function (err, access) {
if (!access) {
return res.status(401).send({ message: 'Invalid password' });
}
access.comparePassword(req.body.password, function (err, isMatch) {
if (!isMatch) {
return res.status(401).send({ message: 'Invalid password' });
}
res.send({ tokenauth: createAccessToken(access) });
});
});
getPasswords();
});
app.post('/auth/signupaccess', function (req, res) {
Access.findOne({ password: req.body.password }, function (err, existingPw) {
if (existingPw) {
return res.status(409).send({ message: 'Password is already taken' });
}
var access = new Access({
password: req.body.password
});
access.save(function (err, result) {
if (err) {
res.status(500).send({ message: err.message });
}
res.send({ tokenauth: createAccessToken(result) });
});
});
});
ComparePassword and save schema
accessSchema.pre('save', function (next) {
var access = this;
bcrypt.genSalt(10, function (err, salt) {
bcrypt.hash(access.password, salt, function (err, hash) {
access.password = hash;
next();
});
});
});
accessSchema.methods.comparePassword = function (password, done) {
bcrypt.compare(password, this.password, function (err, isMatch) {
done(err, isMatch);
});
};
the creation of the password works and is correctly encrypted and inserted into the database. But when I try to login it throws the 401 error inside app.post('/auth/loginaccess').
Why is this happening?
And any tips to improve this is highly appreciated.

Angular firebase, cant login using factory

I get an error when i try to login using this code. The part of creating the user works perfectly and the login methods I used are nearly identical. But chrome gives me this error message:
TypeError: undefined is not a function
at Object.loginUser (http://localhost:8080/js/app.js:28:10)
at Scope.HomeController.$scope.loginUser (http://localhost:8080/js/app.js:197:9)
This is the html:
<button ng-click="createUser(email, password)">Create user</button>
<button ng-click="loginUser(email, password)">Login</button>
In the controller:
$scope.createUser = function(email, password) {
Auth.createUser(email, password);
}
$scope.loginUser = function(email, password) {
Auth.loginUser(email, password);
}
And the factory:
(function () {
angular
.module("myQuiz")
.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
var ref = new Firebase("https://angularquiz.firebaseio.com/");
return {
createUser: function(email, password) {
ref.createUser({
email: email,
password: password
}, function(error, userData) {
if(error) {
console.log("Error creating user: ", error);
} else {
console.log("Succesfully created an account with uid: " + userData.uid);
}
});
},
loginUser: function(email, password) {
ref.authwithPassword({
email: email,
password: password
}, function(error, authData) {
if(error) {
console.log("Login failed! " + error);
} else {
console.log(authData + "Succesfully authenticated!");
}
});
}
}
}]);
})();
typo, its authWithPassword not authwithPassword!
it works now

Resources