Create API Key and verify cross-domain in nodejs - angularjs

I'm new to nodejs, and I'm trying to create and REST_API server, the thing is:
1- I have user registration and login currently working using passport
What i am a bit confuse is:
When a user get access to they're dashboard, i want to have and button that says (Generate your API Key). Then the user will use this key in header requests to my REST_API. That's where i'm not understanding, what should i use to get the above flow?
I tried using JWT to generate a token, but that was only creating the token when user login, and i don't want the user to have to login everytime.
Here's my login route:
app.post('/api/login', passport.authenticate('local-login'), function (req, res) {
res.json({ message: req.authInfo, user_id: req.user.id, user_email: req.user.local.email, loggedin: true });
});
If there's something else i have to provide, please ask ok?
Thanks!

When a user get access to they're dashboard...
Make a post request to an endpoint, pass the userid, that way you will know which user the key it’s been generated . Generate the key and return it. You can store it in cache or session to use during the session
i don't want the user to have to login overtime...
If you don’t want to make your user login everytime. You could store user and pass in browser cache(encrypt the pass). so, when user heads to the app you have to check if user and pass are in cache. if so, log the user in.

Related

Creating a user client side without auto login Meteor

For an app im making using Meteor i have the function to add users on the client app however if i just call the Accounts.createUser it automatically logs in to the new users' account. To get around this i am currently calling a server side method and just passing the data in the Meteor.call() below. I am pretty sure that this passes the password as plain text to the server which is bad.
Is there any way for me to make sure the data is securely sent to the server method without it automatically logging the user in?
Meteor.call('serverCreateUser', username, password, phone, email, admin)
I am pretty sure that this passes the password as plain text to the server which is bad.
Using a standard Meteor method, yes. This is why you should always use https in production!
There is, however a different approach you can implement. You can actually create a user, without providing a password, then nobody can login with this account. You then send an enrollment email to this user, requiring the user to set an initial password, which is then hashed, before being sent over the wires:
Meteor.methods({
'serverCreateUser' (username, phone, email) {
// server should consider based on server-only rules, whether
// a user will be an admin!
const userId = Accounts.createUser({ username, email })
// set profile fields
Meteor.users.update(userId, { $set: { phone })
// send enrollment mail
Accounts.sendEnrollmentEmail(userId)
// return new user id
return userId
}
})
When on the client the user sets the initial password it will use Accounts.resetPassword.
Note, that this still requires https, because a hashed password is still not an encrypted password.

How do you change what gets displayed on a front-end (Angular) view based on properties in your JWT token?

I'm pretty new to working with tokens. Just started learning yesterday.
I have an Express backend API. I understand that the token prevents anyone from getting access to data on any given API endpoint/json data...But how can I READ/decrypt the JWT when it's on the angular side?
I.E., Okay, I know that this user is logged in and can therefore view this page, however, this particular user is the CREATOR of this event. Therefore, on this event's show page, users who have been invited are allowed to view it, and so is the event creator, but only the event creator will see a button that when clicked, does a delete request to the event. The other users will not see this button.
The only way I see this being possible is that the JWT containing the user object can be decoded on the front/end, then I have access to variables with the decoded JWT properties. I.E., username and userID. That way, on the view page being rendered in Angular, I can code logic such as:
```
if (decodedJWT.user.username === event.creator.username) {
DO SOMETHING HERE LIKE DISPLAY A CERTAIN BUTTON
}
```
Thanks.
You need to create an API point in your nodeJS backend that will return the user details if he is logged in:
app.use('/userinfo', expressJwt({secret: secret}));
Here you make sure /userinfo is protected by JWT and your secret phrase.
Then the route corresponding to this API returns user info:
router.get('/get', function (request, response) {
response.json({
id: request.user.id,
name: request.user.nom,
email: request.user.email,
role: request.user.role
});
});
The full API is located at /userinfo/get and is secured by the JWT token.
In angularJS you just need to make a request to that API using simple $http.get('/userinfo/get') which will return a user object or an error from the server if not logged in.
Of course you need to pass the token to all your $http requests.

AngularJS: is this a bad practice for authentification?

I'm new in AngularJS. I use Drupal as Backend for APIs.
So this is my problem:
When the user is logged-in, Drupal saves automatically the SessionNAME = SessionID in the cookie to keep the user logged-in so on refresh the user is still logged-in but i loose the userId, the username, his email, his favorite movies...
My solution was: sending a request to the server in app.run() to get logged user data and I store these data in AuthetificationService.currentUser so if a user is logged i will have all his data otherwise currentUser will be NULL.
Is that a bad practise?
NOTE: Please if your suggestion will be webStorage or cookieStorage tell me exactly what i need to store and when i need to empty the cookie or the local-storage.
Here's the practice I follow and is usually used:
Login->
create session on server ->
store the user object and important info in localstorage
e.g.
localStorage.setObject("myApp_user",user);
localStorage.setObject("myApp_movies",movies);
Refresh Page (check session)
check session(if logged in) ->
get the user data from localStorage and use it
e.g
UserService.user = localStorage.getObject("myApp_user");
MoviesService.movies = localStorage.getObject("myApp_movies");
Logout
close session call on server->remove cookies->remove data from localStorage.. e.g.
localStorage.removeItem("myApp_user");
localStorage.removeItem("myApp_movies");
Hope this helps.

How To Sign Up A New User To My Website Using Facebook

I have a relatively simple question that I am having trouble finding the answer to. I want to set up a way for users to sign up for and log into my site using Facebook. I have been through tutorials which show me processes I need to go through in order to enable my website to communicate with Facebook.
My question is: Once I can communicate with Facebook, how do I then sign a user up permanently on my site? Do I pull information about the user from Facebook and just create a profile for them on my site using that information? Wouldn't I need to then associate that user's unique Facebook ID with the profile I create for them on my website. It seems like I will have to alter my databases in order to accommodate logging in through Facebook. Am I on the right track?
You can authorize/reauthorize a User with Facebook even without any Database, but if you want to store data for the User (name, email, ...) or connect it to an existing User account in your Database, you can store the unique ID.
Use FB.login to authorize with Facebook and FB.getLoginStatus to refresh the User session and to check if a returning User authorized your App already. The User ID is in the callback response of those functions, for example:
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
//user is authorized
console.log(response.authResponse.userID);
} else {
//user is not authorized or not logged in on facebook
}
});
Careful though, it is an "App Scoped ID" and only valid for one specific App. See changelog for more information: https://developers.facebook.com/docs/apps/changelog
Btw, here´s an article about Login with the JavaScrip SDK: http://www.devils-heaven.com/facebook-javascript-sdk-login/

What is the correct way to use Laravel basic auth with angularjs?

Here is the approach that I follow.
I secure the routes for my API like this:
Route::group(array('prefix' => '/api/v1'), function () {
Route::get('dashboard', array('before' => 'basic.once', function () {
return 'Dashboard';
}));
});
I am planning to use basic auth over an SSL connection.
I have to send username and password to the with every request.
I understand that I need to store some user details on the client side (angular/browser) so that the user logs in once and is allowed to access protected routes until his session is valid.
What I don't understand is what user information do I store at the client end and how?
The API will be used for building mobile apps in future.
What is the simplest thing I can do to achieve this?
The simplest way is that when a user register (or you create a user), you add an extra field not just the standard credentials (username, password), this extra field can be token what you'll generate when you create the user, after that when your user logs in you send back to him this unique token, and at client side (angularJS) you can store this token for example in session storage, and after this you need to send this token with every API call. To simplify the back-end you can make a filter to test the token and log in the user. This will be important if you want to use your application on mobile devices where aren't cookies, so you will log in the users with every call.

Resources