How to assert If the signature is valid in the url - Laravel, TDD - laravel

I have a rating & review form which is used by the customers to submit their reviews. This form can be accessed using a url even if they are not signed-in to the platform.
I use signed routes to prevent anyone from submitting the form. The url is shared to them via email. The url looks like below:
http://localhost:8000/review?order_id=12345&signature=c95c7d59e240d97c5d4ceaa0fe4d75a9a100871a0d36b8a997f5a4c4f4567777
If someone tries to submit the form without the signature or invalid signature or invalid order_id, an error is thrown. Each signature is unique to an order_id.
I create signed route using below code:
$signed_url = URL::signedRoute('add-review', ['order_id' => $newOrder->id], null, false);
I am writing a test case to check if the signature exists and is valid but I can't seem to find an assert that I could use to check if signature is valid.
The only asserts I found which is for signed route is:
assertRedirectToSignedRoute
https://laravel.com/docs/9.x/http-tests#assert-redirect-to-signed-route
I do not redirect user to a signed route, instead I store the url in the database and attach the url when an email is sent.
The code I use in the controller to do the check is
if (! $request->hasValidRelativeSignature()) {
throw new HttpResponseException(response()->json([], 403));
}

Why not fetch the url to the database and use assertEqual() to test if the signed url and the url related to the order ID is equal

Related

How does Djoser account verification system really works under the hood?

So I'm currently in an attempt to make my own account verification system and I'm using some parts of Djoser as a reference. let me try to walk you to my question
Let's say you're to make a new account in Djoser app
you put in the information of your soon to be made account including email
submit the form to the backend
get an email to the whatever email account you put in earlier to verify your account
click the link in your email
get to the verify account page
now in this page there's a button to submit a UID and a token and both of those information lies in the URL.
My question is:
What are those tokens? is it JWT?
How do they work?
How can I implement that in my own projects without djoser?
The answers to your questions are immersed in the own code of djoser.
You can check djoser.email file and in the classes there, they are few methods get_context_data().
def get_context_data(self):
context = super().get_context_data()
user = context.get("user")
context["uid"] = utils.encode_uid(user.pk)
context["token"] = default_token_generator.make_token(user)
context["url"] = settings.ACTIVATION_URL.format(**context)
return context
So get the context in the class where is instance, and in this context add the 'uid' (this is basically str(pk) and coded in base64, check encode_uid()), the 'token' (just a random string created with a Django function from your Secret key; you can change the algorithm of that function and the duration of this token with PASSWORD_RESET_TIMEOUT setting) to use temporary links, and finally the URL according the action which is performed (in this case the email activation).
Other point to consider is in each of this classes has template assigned and you can override it.
Now, in the views, specifically in UserViewSet and its actions perform_create(), perform_update() and resend_activation(), if the Djoser setting SEND_ACTIVATION_EMAIL is True, call to ActivationEmail to send an email to the user address.
def perform_create(self, serializer):
user = serializer.save()
signals.user_registered.send(
sender=self.__class__, user=user, request=self.request
)
context = {"user": user}
to = [get_user_email(user)]
if settings.SEND_ACTIVATION_EMAIL:
settings.EMAIL.activation(self.request, context).send(to)
...
The email is sent and when a user click the link, whether the token is still valid and uid match (djoser.UidAndTokenSerializer), the action activation() of the same View is executed. Change the user flag 'is_active' to True and it may sent another email to confirm the activation.
If you want code your own version, as you can see, you only have to create a random token, generate some uid to identify the user in the way that you prefer. Code a pair of views that send emails with templates that permit the activation.

How does Laravel interally create certain parts of the verification email?

When creating a verification email with Laravel this is how the link can end up looking:
.../verify/1/3f4f10efdbac36ec6892bb3572ac6683ff663ad8?expires=1641580767&signature=babf2d50deb610a551d0477132193abb595d8664b56a9074c38f5b3789933ad
After the "verify/1/" there seems to be some hash of length 40.
The last query parameter "signature" has a hash of length 60.
My questions are: How are these hashes created? Which hash function is used and what is the input string? Also what is the purpose of those parts?
1- The first part after the verify/1/ is the sha1 of the registered user email.
We use this to make sure we validate the same email we have in the db and the one the user registered with.
2- The last part of the url is a sha256 signature to make sure the url is not altered by a malicious user. Any modification to the url will make the signature fails. Note that the signature is checked with the Laravel Signed middleware
So it is basically security measures to prevent malicious user.
For more informations:
The generated link will be in the notification class here: src/Illuminate/Auth/Notifications/VerifyEmail.php
Once the user clicked the link, it will be processed and checked in the file below: vendor/laravel/ui/auth-backend/VerifiesEmails.php

Codeigniter route with JWT as parameter not working as expected for some users

I have a url like the one below with a parameter as JWT token.
http://localhost/activate/khjdfbhdfgkfgyuyi674.gsdgfhksgdkfjbsdfghgsdfkdsfhsdfjsdufisdf.jhsdfkjsdfhjshdf
I have a function in my controller that handles this route i.e
function index($token) {
// $token is the jwt token from the url
}
In my routes configuration i have the route defined as:
$route['activate/(:any)'] = 'controllername/index/$1'
However some users who access this route end up with $token containing part of the JWT string i.e
khjdfbhdfgkfgyuyi674
And others end up with $token having the full jwt string i.e
khjdfbhdfgkfgyuyi674.gsdgfhksgdkfjbsdfghgsdfkdsfhsdfjsdufisdf.jhsdfkjsdfhjshdf
I have failed to reproduce what the problem could be. Looks like the $token from the parameter is only retrieving the string till the period (.) or user is clicking on the link from their email and only the parts till the period (.) are being triggered!
It was actually a problem with some email clients. We were sending the full url link via email so when some users click the first part of the link, it takes part of the url until the first period (.) which makes it an incomplete link.
So we decided to add a button to the link in the email to avoid such scenarios from happening again.

make ajax parameters secure

I want to send email value in parameters in ajax. I am using following code it is working properly, but I want to make it secure. no user can check or pass invalid value from calling this action in query string or in any other way. How can I make it secure?
$.ajax({
url: '/Application/UserInfo/',
type: 'POST',
data:{email:emailid},
success: function (result) {
var json = eval(result);
}
});
If you dont want anyone to be able to see the value of the email parameter, you should consider using HTTPS.
But for passing invalid values, you should do some validation server side where this value is used
It may help if you are doing it with two steps at all:
First you can check the email having the right format with a regular expression:
/^\w[\w|\.\-\_]+#\w[\w\.\-äöüÄÖÜ]+\.[a-zA-Z]{2,18}$/.test(email);
Then you may crypt the mail and then you can send it safely.
I am using blowfish. On page loading I generate a key that is set to the javascript of my page. Both, javascript and php have a blowfish controler that can crypt and decrypt any value. I am crypting the value on javascript and send it to the server.
There I decrypt it and check it again with regular expression. The key is not sent to server again, its stored somewhere in the session or so.
To take care that the email is correct you can check whether the domain is reachable through curl or so, but I prefer sending a confirmation mail to the adress and wait for an accept with a generated unique token.
If you just want to get sure of a user signed in with google plus account you may get use of the google plus api and check if the user is logged in. If not you don't accept it.

How to handle encrypted URL's in rails?

I am sending email to user, in that email one link is there to redirect that user to rails application. I want that link to be in encrypted form with domain name for example:
https://www.domain_name.com?hdurstihnzdfalgfgdfhdrbnhduolsasrtyumyrtyr
when user click on this link, he should directly redirect to controller method we specified in that URL which is not visible.
Controller and methods given in URL may vary according to user.
So my question is how we can do this in rails.
If I encrypt controller name, method name and parameter we passed. How routes file come to know where to redirect this URL? How to decrypt this in routes file and redirect internally to decrypted URL?
Life will be easier if you can do a slight modification to your url, something like:
https://www.domain_name.com/enc/hdurstihnzdfalgfgdfhdrbnhduolsasrtyumyrtyr
Then you can create a route for that path to redirect where you want.
get '/enc/:encoded_path' => "controller#action"
This would give you access to params[:encoded_path], which would equal hdurstihnzdfalgfgdfhdrbnhduolsasrtyumyrtyr in this case. From there, you could decode in the controller and then redirect however you want.
That's not the right approach. Here's what you can do instead:
Create a new controller action, say for instance, activate.
def activate
activation_token = params[:auth_token]
....
your logic to do whatever with this token
end
Create a corresponding route:
match '/activate' => 'your_awesome_controller#activate'
Now, when you email your users, I'm guessing you're sending some sort of activation token. If not, create two new fields in your users table:
activation_token:string
activated:boolean
Use some unique string generation algorithm to generate your activation_token and email it to your user:
yourdomain.com/activate?auth_token=user.activation_token

Resources