MEAN Stack app authorization - register seems to by trying to login - authentication

When I try to register as a new user I get an error message saying invalid username or password which makes me think the app is trying to login when it should be trying to register.
The form:
form(class='form-auth' ng-submit='register()')
p(class='text-warning'){{error_message}}
label(for='email') Email
input(type="email", ng-model='users.email', name="email", placeholder='Email')
label(for='password') Password
input(type="password", ng-model='users.password', name="password", placeholder='Password')
input(type="submit" class='submitBtn' value='Go')
The 'register' controller (in file 'myApp.js' in the public Javascript directory)
app.controller('authController', function($scope, $rootScope, $http, $location){
$scope.user = {email: '', password: ''};
$scope.error_message = '';
$scope.register = function(){
$http.post('/auth/signup', $scope.user).success(function(data){
if(data.state == 'success'){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$location.path('/');
}
else{
$scope.error_message = data.message;
}
});
};
});
I've got auth and passport in the main app.js file. I have a login function above the register one but it seems to be closed properly. Is there something wrong here?

The ng-model of the inputs should be "user.email, user.password" instead of "users.email, users.password" like its in your controller $scope.user.
Like $scope.users doesnt exist, empty values are sent to the backend.

Related

ExpressJS apply JWT for file url

So I'm trying to make authorization for routes with JWT, it all worked if used on routes.
app.get('/user/list', jwtMiddleware, action);
And the jwtMiddleware content is (more or less):
var token = req.headers.authorization;
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, process.env.SECRET_TOKEN, function(err, decoded) {
if (err) {
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
} else {
// if everything is good, save to request for use in other routes
next();
}
});
} else {
// if there is no token
// return an error
return res.status(401).send({
success: false,
message: 'Sign in to continue.'
});
}
it works, but I have these image files in uploads/ folder which accessible by /upload/image-1.jpg and I want to prevent direct access to /upload/image-1.jpg by using wildcard routes app.get('/upload*', jwtMiddleware, action);
then I try accessing random route with upload prefix like /upload/test, the jwt middleware works. But if I explicitly type /upload/image-1.jpg the browser just show the image, it's like the middleware or wildcard route (/upload*) is not accessed (the console.log inside middleware didn't even fired).
Previously I use restify and restify-jwt-middleware, it could handle this case flawlessly but in express I can't find out why it doesn't work. Maybe because restify-jwt-middleware automatically registers all routes into jwt validation whereas express need to declare each route with jwt middleware manually.
is there anything I miss in this case? thank you.
add/modify to another route like app.get('/upload/:image', jwtMiddleware, action)
this will check all the route you mentioned /upload/*
EDIT :
put the static files(eg.uploaded files somewhere like images/upload) and route them using the serveStaticFiles plugin restify and put jwt middleware to verify the user login status.
server.get(
'/uploads/*',
jwtMiddleware,
restify.plugins.serveStaticFiles('./images/upload')
);
In case anyone still confused, here's my answer in express which is similar approach to yathomasi's
// the fake route
app.get('uploads/:name', jwtMiddleware, (req, res, next) => {
if (fs.existsSync('./realpath/' + req.params.name)) {
res.sendFile('./realpath/' + req.params.name);
} else {
res.status(404).body({status : 'ERROR', message : 'File not found'});
}
});
this way, the uploads/somefile.jpg is treated as route url not file url and will be processed by jwtMiddleware

AWS Cognito JS SDK returning "AdminUpdateUserAttributes is not a function" error message

I'm trying to create a function which allows me to update a user's phone number in a Cognito User Pool. The code is in a NodeJS application, using the latest aws-sdk library.
I have this function callback structure working for a number of other actions against the user pool, e.g. creating and listing users, updating MFA, etc. So I am confident there's nothing structurally wrong with the way I have laid the code out.
But for this particular function, I am receiving an error that says AdminUpdateUserAttributes "is not a function".
I've tried changing different attributes in case it's a phone number thing, but I got the same result.
function cognitoUpdatePhone(username, phoneNumber, callback) {
var params = {
UserPoolId: '<my pool Id>',
Username: username,
UserAttributes: {
phone_number: phoneNumber
}
};
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
cognitoidentityserviceprovider.AdminUpdateUserAttributes(params, function (err, data) {
if (err) {
callback(err, false);
}
else {
callback(null, true);
}
});
}
I'm getting following response from the server. The stack trace indicates the source of the error is: aws-sdk/lib/state_machine.js
message: 'cognitoidentityserviceprovider.AdminUpdateUserAttributes is not a function',
code: 'TypeError',
Encountered the exact same problem. Solved it by changing the first letter of the function to lowercase: adminUpdateUserAttributes
Try using this:
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});

Invalid CSRF when logging in to keystone

I'm entirely new to coding. I've looked around a bit, but not found anything relevant.
When logging into keystone to view our mongoDB database I get an error message saying:
Something went wrong; please refresh your browser and try again.
Doing that does not help. Neither does deleting the browser history or attempting from another lap top.
Looking at the javascript console in the browser, the error states invalid csrf.
I think this is the relevant source code in the keystone folder:
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
How can I go about solving this / debugging the error? Thanks for any help!
This usually happens when session affinity fails. Are you using default in-memory session management? Maybe, try using a database for maintaining session state.
If you use MongoDB, Try the following config setting
'session store': 'mongo',
See 'session store' section under http://keystonejs.com/docs/configuration/#options-database for more details.

What should I consider when I am doing an authentication process with a titanium app?

Hello it's my first time doing a sign in process in a mobile app with Titanium and I wonder what information should I save and the best practice to do it?
My server is configured in this way:
The server requires I send a user and password and if the information match it will provide a token session.
This is the code I use for signing in:
function signIn(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('POST', 'http://myserver');
var params = {
user : $.txtUsuario.value,
password : $.txtPassword.value
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.success == "true")
{
var landing = Alloy.createController("menu").getView();
$.index.close();
landing.open();
}
else
{
alert(response);
}
};
};
the code above is working, however I do not know how to manage the sign out. I would like my application works like the most apps do, e.g:
You sign in once and after that if you do not close the app you are able to continues using it and even making a request.
Thank you for any explanation.
It depends on your app requirements. for exemple if you will use the token in your app later you can save it as an AppProperty :
Ti.App.Properties.setString('token',yourTokenGoHere);
and in the app starting you can get it back :
var myToken = Ti.App.Properties.getString('token');
and then you can make a test for example if the token is still valid or not :
if(myToken === 'invalidtoken')
youSholdLogin();
else
youCanGoFurther();
and when the user disconnect rest the token to be invalid :
Ti.App.Properties.setString('token', 'invalidtoken');

Google Auth2.0 log out

I'm currently trying to make a site where the user can log in with his google+ account. Most of it is working. I get them to grant access to my website. They can log in and I get their name and user ID, and I show content specific to their google account on my site.
When however someone else wants to log in and I try to 'log out' of the site, the google log in still remembers that it just logged in and after logging out it instantly runs the code to log in again. If I delete the SSID cookie from google it doesn't do this, so I'm assuming that's where google stores the fact that I just logged in with x.
Is there a way to when I log out make google not instantly log in with the same account, but rather ask for the e-mail and password of a google user?
I feel like I'm missing something obvious here, but I can't figure out how to deal with this.
Code I use to Auth and get data:
<button class ="btn btn-primary" id="authorize-button" style="visibility: hidden">Log in</button>
<script>
var clientId = '';
var apiKey = '';
var scopes = '';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth,1);
}
function checkAuth() {
//alert("authorize");
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
//alert("authorized");
//alert(authResult.access_token);
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
var token = document.createElement('h4');
token.appendChild(document.createTextNode(authResult.access_token));
document.getElementById('content').appendChild(token);
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
var x;
function makeApiCall() {
//return;
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
x = resp.id;
var heading2 = document.createElement('h4');
var heading3 = document.createElement('h4');
heading3.appendChild(document.createTextNode(resp.displayName));
heading2.appendChild(document.createTextNode(resp.id));
document.getElementById('content2').appendChild(heading2);
document.getElementById('content3').appendChild(heading3);
$.post("token.php", {id: x});
});
});
}
When you make the auth call, set approvalprompt to force. This will force the consent dialog to appear every time. It overrides the default setting of "auto." You can learn more at https://developers.google.com/+/web/signin/#sign-in_button_attributes.
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true, approvalprompt: force}
After the user authorizes your app, they are basically logged in to your app any time that they are also logged in to Google, especially when immediate mode is turned on.
What some sites do is have a logout link or button that displays a page or dialog that says something along the lines of "You're logged in to Google and this site with account blah#blah.com. If you want to switch accounts, go to google.com and log out of your Google session."
You can also track the logged in status of a user using your own cookies and setting and removing them during the appropriate events in your code. You would want to discard any tokens that your app obtained on behalf of the user during a log out event. When the user logged in again, they would not need to re-authorize your application with the popup (or redirect window), but you'd still get a new access token during the callback.