Throttling in Laravel - laravel

Can somebody help me out with Laravel's Throttling ? Right now, my website uses throttling to prevent user from logging in for 'x' seconds, if the password they entered are wrong for 'x' number of time.
After logging in, user will require Two-Factor Authentication to update their information but i would like to throttle the Two-FA too, so that they will be locked out from updating their account. I can actually reuse the login's throttling codes to lock the user out but the issue is that, when the user logs out, they wont be able to log in due to the temporary lock.
I would like to create a custom throttle just for Two-FA and probably prevent the user from accessing that specific route for 'x' seconds.
I have tried searching around, but everything is related to login. If somebody could suggest me a package which will fit my requirement or provide a simple tut. will really be helpful to me. Thanks for your time.

This is all outlined in the ThrottlesLogins trait, but I'll try to simplify it even further.
Generate a unique key for the user and type of request:
$key = '2fa:' . $user->id;
Add a hit (increment count) on every request to the endpoint using the Illuminate\Cache\RateLimiter class:
app(RateLimiter::class)->hit($key, $timeoutInMinutes);
Check if the limit has been reached before processing the request:
$bool = app(RateLimiter::class)->tooManyAttempts($key, $maxAttempts, $timeoutInMinutes);

Related

Getting the number of users online on a specific post

I have some blog with some posts. Every page has a block "Read now" which contains post titles with count of readers at that moment (guests and auth users).The question is how to get these counters.
I am usinng laravel Echo with beyondcode/laravel-websockets.
Tryed to using presence channel, but it requires authorization.
You can try this method by SaeedPrez.
Alternatively, you could try going through Laravels Request like this:
Request::session()->all()
Try dumping and dying (dd() function) and see how you could parse the given response. As an idea maybe use a CRON and save the variables in cache.
I think you can try init Echo.listen() on public channel once user hit the post page. From that, you can build logic to see how many people are in that post.id page by temporarily store the count data somewhere in Redis or just in database the belong to that specific post. And remove the count when user leave the page by calling the Echo.leave().
There's no true solution yet since presence channel require authenticated user.

Hidden authentication in some websites

I find that some websites have sort of authentication even though no user is logged in. Taking plunker for example, even a non-logged in user can freeze a snippet such that other users cannot modify; whereas the user himself could always modify the snippet even though he opens the link in another browser tab.
My current solution is adding a type field (ie, anonym and normal) in the user model. Then, each time there is no normal user logged in, I systematically generate a unique random ID, register and login as an anonym user. It works, but the shortcoming is there are lots of anonym users in my database.
Does anyone have a better solution? Is there any "standard" way to realize this kind of hidden authentication?
I think method you are looking for is called session id. When you save as anonymous user web app creates a session with a session id which is used to identify the user by link. For example on plnkr it'll be something like https://plnkr.co/edit/session_id?p=catalogue where session_id is some sort of hash.
To freeze the snippet the session id is written into cookies with the flag, saying, for example, that the state is frozen. If you freeze it in Chrome and open in a Chrome's private window or in Firefox on the same computer, you wouldn't be able to unfreeze it. It'll behave the same way as for other users which have no cookies. In fact using session hash for cookies, rather than any user identification is better for security reasons.
Now this approach in a sense isn't any better, than creating anonymous users - you still have to save session records into the database to be able to open session context by link. In fact, it might happen to be simpler in your case to do exactly what you did if user is assumed to be present in lots of use cases and places in the code.
In many cases, however, separation of session from user makes lots of sense as it simplifies keeping session state after login or registration. Say some web stores would empty your basket after you register, causing quite a bit of frustration, especially if you put several small items into it which you now have to find again and put back. Those don't have sessions or don't use them correctly on registration or login.
Otherwise, as I wrote it's pretty much the same and you have to deal with many anonymous sessions which pollute the database unless you have some sort of wise retention policy, depending on you use case. Say, for example, a web site similar to plnkr.co which is used to share code snippets, and post them on sites such as stackoverflow should better keep those sessions while there are users accessing those say at least once a year. So sessions should have access date and policy would be that it's older than 1 year.
Hope it helps.
I have done similar using Local Storage. It allows you to store data on the browser. A user can then open tabs, close browser completely and reopen etc and the data is still there. It would then appear to be saved for them but actually it's just stored on their browser.
This wouldn't allow others to see what they have done though, so not sure if this is quite what you're after.
I wrapped them in functions in case I chose to change them out later, something like this
StoreLocalVariable: function (key, value) {
localStorage.setItem(key, value);
},
GetLocalVariable: function (key) {
return localStorage.getItem(key);
},
Some info including compatibility
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

Check availability of resource used by another user

Building a web application.
User have access trough their browser to shared resources host on a server, however if UserA is already using Resource1, Resource1 should not be available to UserB until UserA release Resource1 or until a given amount of time.
For this part : I chose to use a MySQL table with a list of tuples (resource,currentuser) and run a cron task to delete expired tuples.
Now I want to be able to notify UserA that UserB wants to access Resource1 and if get not answer from UserA, then UserA lost his lock on Resource1 and then the Resource is then available to UserB.
For this part, I guess I have to use AJAX. I have thought about the following solution :
User's browser make periodic AJAX call (let's say each minute) to prove he is still alive and upon a call, if another User has requested the same resource, he has to challenge a server request in a given amount of time(for example a captcha). If the challenge fails, it means the user is not here anymore (maybe he left his browser opened or the webpage unfocused).
The tricky part is : "he has to challenge a server request in a given amount of time (for example a captcha)". How to do that?
Am I following the best path ?
Yes, what you've outlined is fine. Using ajax is also completely fine, especially if you're simply polling every minute.
For example, let's say you have the following:
setInterval(function() {
$.get('/resource/status', function(response) {
if (response.data.newRequest) {
//This would signal a new request to the resource
}
})
}, 60000)
When handling the new request to access the resource, you could use something like reCaptcha and display that however appropriate (overlay or inline). When you do this, you could also start a timer to determine if it's exceeded the amount of time allocated or not. If it has, then you can do another ajax request and revoke this person's access to the resource, or however you want to handle that.
i would use web sockets to control all the users that need to get the resource.
this way you will know who is connected and using the resource and when he finish using it you can let the next user the resource and so on ,
(this way can tell each user an estimation of how much time it will take him to get the resource and do some progress bar)
I think there're two problems here.
How to notify users that resource becomes available?
Periodic AJAX requests might be okay, but you can also consider long-polling or websockets to get close to notifying waiting users in real time.
How to find out that resource is still used by user?
If you want to catch the moment when human user is not doing anything on page, you can track mouse movement/clicking or keyboard button pressing. If nothing is done for last n minutes, the page might be considered as not active.
If you want to make sure that page is not exploited by automated software, you can ask to fill in captcha once in n minutes when resource is being used.

Mixpanel alias on multiple devices

I'm confused by the way that Mixpanel alias() is supposed to work, despite the fact that Mixpanel have multiple pages attempting to explain it.
According to this page, I should call alias() only once per user, because it will create a one-time mapping from their user ID to the device's generated ID. But shouldn't that mapping be the other way around? Let's say Bob starts my app on his phone and logs in, at which point I call alias() to map all his actions so far to his account. He then goes through the same process on his tablet - I would expect that I can then call alias() on that machine to do the same thing. But the page I mentioned specifically says not to do that, because it will map his user ID to that device's ID now.
I can call identify() on the multiple devices, but that does not link his previous events to his user ID.
I feel like I'm misunderstanding how this whole thing works, but I've now spent a few hours pondering this so I'm hoping it's confused someone else in the past too...
I always understood alias() as mapping the identifiers both ways. I've had a similar case as you. I'm almost sure that it does not matter how many times you alias and in which direction you alias the identifiers.
This is not authoritative though, but rather based on past usage and possibly-flawed understanding.
As they explain on their help documentation:
https://mixpanel.com/help/questions/articles/how-should-i-handle-my-user-identity-with-the-mixpanel-javascript-library
Ideal implementation
The ideal integration that will allow you to track users from anonymous browsing all the way through signup and subsequent logins:
When a new user signs up, call (once)
mixpanel.alias("YOUR_USER_ID")
When a user logs in, call
mixpanel.identify("YOUR_USER_ID")
Applying this to your question, you need to use identify when the user do login with the mobile and another time when he do it with the tablet.

Using forms authentication, is it possible to switch the logged in user in code, just for the current request?

In a certain situation, I want a request to execute as a user different than the one actually logged in. So, when User A requests a particular page, from code I want to switch it execute under the user account of User B -- only for this single request (or even for a single block of code...)
I've used this:
FormsAuthentication.SetAuthCookie("UserB")
This works, but it's persistent. When I request a new page, I'm now logged in as User B, which is not what I want.
Is this possible? I've RTFM'd up and down for this.
Edit: I may have found an answer, which I posted below. Looking for confirmation or refutation of this solution.
I think I might have found it. I'm not 100% sure, but this works. I just don't know if it's completely correct or if there's something I'm not considering.
HttpContext.Current.User = PrincipalInfo.CreatePrincipal("UserB");
Again, this seems to do what I originally wanted. If you have experience that would prove me right or wrong, please comment.

Resources