Before login hook drupal 8 - hook

I am very new to Drupal. Is there a hook on drupal 8 for pre-login ?
I would like to redirect the login information of a user on a web server by URL (web services).
I know that there is the user_login hook, but this one only looks called once the user is connected to the drupal database. I would like to retrieve the step before, so the login and password information
Thank you !

You can use a hook_form_alter on the login form and add your submit handler before the actual form submit handler. If this doesn't make sense I can post some codes.
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'user_login_block':
case 'user_login' :
array_unshift($form['#submit'], 'custom_login_submit');
break;
}
}
/**
* Custom submit handler
*/
function custom_login_submit($form, &$form_state) {
//code here
}

Related

firebase onAuthStateChanged infinite loop node js

I'm using firebase to sign in my users on my node js app. I would like to see if the user is authentificated or not and after it redirect to the page I want (login if it not logged or dashboard).
But when I redirect user (if it not logged previously or session expires) it's looping on the same page (send redirect of the login page everytime when I'm on login page).
My function that I use actually :
function authenficated (req, res, next) {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
console.log("connected" + " " + user.uid);
next()
} else {
console.log("disconnected")
res.redirect('/') //loop on / page
next()
}
});
}
I would like a function that provides if my user is logged or not, if it logged my node backend return to /dashboard or other pages that I want and if not it cannot access to dashboard and it return automatically to / or /login
I specify I don't use React or Vue, I use simply EJS to display my pages
Thanks for all
This function/sdk is meant for frontend applications and not backend apps. You need to the admin sdk for that. You can use cookies and the admin sdk provides a function to create cookies. After a signin you attach the cookie to the headers and it will be send by the browser on every request. If the cookie header is empty than you know the user isn't signed in. To logout a user you can add a head method to clear the cookie.
To use backend function you need to use the admin sdk. This function is a front end function (web sdk ).
You can use onAuthStateChanged on the front end and redirect them from the front end. Remember onAuthStateChanged will fire on every page load.
OR implement cookies like the previous comments.
OR
Send the id token from the client via http request (fetch or axios) and verify server side using the admin sdk. Here is the specific link. This solution would require you to load something on the front end though and then send a http request to the backend, verify, then send protected resources after.
Cookies on the other hand are sent to the backend with every request, so if no cookie is present on the page load request then obviously there is no user. Or if the below function fails then server wont send protected resources. (this is explained in the link above for cookies)
getAuth().verifySessionCookie(sessionCookie, true /** checkRevoked */)

Catching dialog name before being routed - middleware

I have a bot built with MS bot framework, using a library structure.
I'm trying to catch the dialog name + library of a message, before it is being routed to the dialog. (for analytics purposes)
Is there a middleware that can help me do that?
I tried the routing middleware of the UniversalBot, but it seems be running just before a dialog was choosen.
One possible option here could be using the ISessionMiddleware.
botbuilder: function (session, next) {
console.log(session.message.text);
next();
}
This will allow you to have access to the session. This will execute once a message is bound to a particular session and gives the option of looking at a message and the state of the session (where user is in available dialogs, etc) then making a decision of how to proceed.
It seems like bot.onDisambiguateRoute is the solution.
The var route contains the route name/library in that case, and has also the dialog arguments besides that. see the docs for more info
example code:
bot.onDisambiguateRoute(function (session, routes) {
// Route message as normal
var route = builder.Library.bestRouteResult(routes, session.dialogStack(), bot.name);
// *** log route
if (route) {
bot.library(route.libraryName).selectRoute(session, route);
} else {
// Just let the active dialog process the message
session.routeToActiveDialog();
}
}
});

Angular 2 (4/5) check if user authenticated, best practices

I am new to Angular and implementing authentication for users.
Most of suggestions on the web propose to save session/username in local storage and when user is back to the app, check local storage in order to display proper navigation (in my navbar I have different nav buttons for private and public views).
However, I found this solution having some drawbacks. For example, if session on server expired, or local storage was manually added, then when app will be initialising, it will show wrong buttons in navbar.
After that I came to solution - to use service before showing navbar buttons, to send request to server to verify if user from local storage with his session is currently active. And only after that I will display nav buttons.
Here comes a question: is it the most efficient way to proof check if user from local storage is logged in and session is active?
There is another way, which I was thinking, but didn't find solution.
Since my angular webapp and nodejs server are located in two different places, is it possible for the webapp to check authentication status (make a request from webapp server to my nodejs server) when index.html is requested and respond with pre-rendered navbar and user status (logged in or not)?
Thanks.
P.S. I am using PassportJS and Express on server side.
The best practise is to use AuthGuard and implement CanActivate to check whether user can view a particular part of the application. Also an authentication service is used normally to let the user login to system and gain an access token.
This access token is then used as Authorisation-Header on each request to server (this is where they will be in sync).
You will need to check for JWT/or any other type token on load which contains user information plus session time out.
If the token is invalid you simply redirect the user to login, otherwise it will allow user to go where they wanted to.
A practical example can be found here.
To have navbar showing different elements for authenticated and non-authenticated users, one of possible solutions will be
To use some "/auth-check" request in authentication.service.ts, which will have trigger every time an event of the result of checking authorisation of current user
...
interface ShareObj { [id: string]: any; }
...
currentUserId: ShareObj = {};
currentUserUsername: ShareObj = {};
public authenticatedBehavior = new ReplaySubject(1);
authCheck(): any {
return this.http.get('/api/auth-check')
.map((resp: any) => {
if (resp.authanticated) {
this.currentUserId['global'] = resp.user.id;
this.currentUserUsername['global'] = resp.user.username;
this.authenticatedBehavior.next(true);
} else {
this.authenticatedBehavior.next(false);
this.currentUserId['global'] = null;
this.currentUserUsername['global'] = null;
}
return resp;
})
.catch(e => {
this.authenticatedBehavior.next(false);
this.currentUserId['global'] = null;
this.currentUserUsername['global'] = null;
});
}
So, in navbar.component.ts there should be a listener for this event:
ngOnInit() {
this.authService.authenticatedBehavior
.subscribe(
data => {
// do change of UI of navbar depending if user logged in or not
}
);
}
To have error-iterceptor.ts file, where you should "catch" all failed requests and check them for Unauthorised response (401). If you catch such response, do authCheck() in authentication.service.ts to make sure that session of current user expired and notify all components which listen for authenticatedBehavior

Using spotify-web-api-node to generate an authentication token

I am new to using nodejs and am working on a project where I can make a custom playlist by adding one song at a time via a search. I've been able to get the code to do the searching and grabbing the proper ids done, but when trying to add to the playlist, I'm getting an error about the scope being wrong. Long story short, I was doing the wrong type of authentication.
So I read up on the spotify-web-api-node documents, but I'm getting lost between generating the authorization url and then getting the response, which is then used by another method to get the authorization token. I'm not sure if there is another method I'm not seeing that will make the request, or if I'm just supposed to do a regular request out via normal node methods.
The code I'm using is pretty much a copy-paste from the following link (https://github.com/thelinmichael/spotify-web-api-node#authorization), where the second box with the header "The below uses a hardcoded authorization code..." is where I'm lost... I need to get that code from the response, but I'm not sure how I'm to send the request to even get the response, the createAuthorizeURL method just seems to make the actual url but not send it.
I believe the confusion stems from the way the Authorization Code flow works, and the way I've written the documentation for the node wrapper. The purpose of the createAuthorizeURL method is to help you create the URL that you need to forward the user to.
From the same piece of documentation that you linked to:
In order to get permissions, you need to direct the user to our Accounts service.
Generate the URL by using the wrapper's authorization URL method.
So let's say that the user starts out by entering your site, http://www.jd.example.com. It'll have a Spotify styled button that says Login here. The button links to the URL that the createAuthorizeURL has generated. One very important part of the URL is the redirect_uri query parameter. For example, the URL that you would generate would look something like
https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&
response_type=code&redirect_uri=https://www.jd.example.com/callback&
scope=playlist-modify-public
When the user clicks the button they will be taken through the authentication and authorization flow on Spotify's site (accounts.spotify.com/). However, when they've finished this flow, they will be directed by Spotify to the same redirect_uri that you gave in the createAuthorizeURL, e.g. https://www.jd.example.com/callback.
This means that your web server (e.g. Express) needs to be able to handle a request to the redirect_uri. If your web server was indeed Express, it may look like this.
/* Some express.js setup here */
/* Some spotify-web-api-node setup here */
/* Handle authorization callback from Spotify */
app.get('/callback', function(req, res) {
/* Read query parameters */
var code = req.query.code; // Read the authorization code from the query parameters
var state = req.query.state; // (Optional) Read the state from the query parameter
/* Get the access token! */
spotifyApi.authorizationCodeGrant(code)
.then(function(data) {
console.log('The token expires in ' + data['expires_in']);
console.log('The access token is ' + data['access_token']);
console.log('The refresh token is ' + data['refresh_token']);
/* Ok. We've got the access token!
Save the access token for this user somewhere so that you can use it again.
Cookie? Local storage?
*/
/* Redirecting back to the main page! :-) */
res.redirect('/');
}, function(err) {
res.status(err.code);
res.send(err.message);
}
});
});
Hope this helps!

How can I stop a user from accessing another route in a single page app directly in Backbone and Nodejs?

I am building an app that requires a login which if successful, passes you off to another page called events. However, Backbone works with the hash in the URL bar, therefore, the request that someone accessed that page is never sent to NodeJs Server.
The thing is, someone without login can access the page by just typing in http://www.mywebsite.com/#events
How can this be prevented?
Overwrite the 'execute' function in the backbone router.
From the docs:
router.execute(callback, args)
This method is called internally within the router, whenever a route
matches and its corresponding callback is about to be executed.
Override it to perform custom parsing or wrapping of your routes, for
example, to parse query strings before handing them to your route
callback, like so:
So, for example: (http://plnkr.co/edit/BqD4YfjQYz2RITWNhBKZ?p=preview)
var Router = Backbone.Router.extend({
execute: function(callback, args) {
if(!someLoginFunctionCheck()) {
this.navigate('#')
} else {
if (callback) callback.apply(this, args);
}
}
});

Resources