Redirect with data - go

After successful create user Model (for example) I need to redirect request to... for example root page. But I wanna send message for ex. "User has been created!".
i can redirect with:
c.Redirect(http.StatusCreated, "/")
but how I can add message?
I tried (guess it was bad idea)
c.Set("message": "Message")
and in root page
s.MustGet("message")
but if root page loads without payload message it complain with panic.
Pls suggest best way for redirection with data.
EDIT
Unfortunately c.Set() doesn't work, guess it's because of redirect.
Maybe some one suggest any tip to send data to redirect?

You can always call c.GetString("message") instead of c.MustGet("message")
MustGet panics if the key does not exist as opposed to Get which lets you handle existence of key and Get sounds more appropriate for your use-case

For case with Redirect it is impossible send data in requests. So in this case uses Session.
According to DOCUMENTATION
r := gin.Default()
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))
session.Set("message", "Oh-ho!")
session.Save()

Related

How to use custom error settings for JWT middleware

I have followed the cook books guide to the letter, found here https://echo.labstack.com/cookbook/jwt
But when using the JWT middleware I am having some issues with adding custom error messages. Login works fine, even to the point of not giving details (username & password) that returns a 404.
But when the JWT is missing it returns a 400, I want it to also return a 404.
So in my research I found this, https://forum.labstack.com/t/custom-error-message-in-jwt-middleware/325/3 which lists the following middleware.ErrJWTMissing & middleware.ErrJWTInvalid But is very unclear on how to set these?
I have tried setting them as vars on the router file, like so
var (
ErrJWTInvalid = echo.NewHTTPError(http.StatusTeapot, "test 104")
ErrJWTMissing = echo.NewHTTPError(http.StatusTeapot, "test 103")
)
But the error that sill comes back to me is a 400 and not a 418 (as this is just a test). So what am I doing wrong?
You can change the HTTP code and message this way.
func init() {
middleware.ErrJWTMissing.Code = 401
middleware.ErrJWTMissing.Message = "Unauthorized"
}
First, a point on your statement that you want to return a 400 and also a 404 error - you cannot do this. You're sending one response from the server so it gets exactly one response code. You could send a 207, but we're not really talking about multiple resources here, so don't do that. In my opinion, a 400 error is indeed the correct response for a missing JWT as that constitutes a bad request. A 404 "Not Found" means that the requested resource (the thing on the server side) could not be found. It does not mean that something in the request could not be found.
As for setting your custom error message, you're likely to be out of luck without altering the source code for Echo. That specific response is coming from within the middleware handlers of the package itself (you can see it here). This is mostly abstracted away from you, so without looking at the inner workings of the package, there would be no way to tell where this was coming from, and frankly there's not a lot that you can easily do about it. ErrJWTMissing is indeed the variable that the package uses internally for this error message, but Echo does not appear to provide an exported setter method for you to change this value, so you're stuck with what it is.
If you truly wanted to set a custom error method for this case I think your options would be to:
Write your own middleware to intercept the request before it was handled by Echo's middleware, where you could handle the request however you wanted.
Edit the Echo source to work how you wanted it to work -- specifically, all you would have to do is edit ErrJWTMissing.
Basically, Echo is trying to do you favors by handling all of this middleware processing for you, and it's a lot of work or hackery to un-do that work while still using Echo.

How is gorilla/context different from gorilla/sessions?

I get sessions, coming from PHP I used to
<?php
session_start();
$_SESSION["key"] = "val";
echo $_SESSION["key"];
?>
Set one or more keys and their values serverside and be able to retrieve or overwrite it until the session expires.
The same with gorilla/sessions
var(
sessionStore *sessions.CookieStore
sessionSecret []byte = make([]byte, 64)
session *sessions.Session
)
func init(){
sessionSecret = []byte("12345678901234567890123456789012")
sessionStore = sessions.NewCookieStore(sessionSecret)
session = sessions.NewSession(sessionStore, "session_name")
}
func SetSessionHandler(w http.ResponseWriter, r *http.Request) {
session, _ = sessionStore.Get(r, "session_name")
session.Values["key"] = "val"
session.Save(r, w)
}
func GetSessionHandler(w http.ResponseWriter, r *http.Request) {
session, _ = sessionStore.Get(r, "session_name")
fmt.FPrintln(session.Values["key"])
}
Now I don't get what the point of gorilla/context is.
I know what a context is but... I don't know how it fits in the big picture.
It says that it's bound to the current request. Another question here on stackoverflow said that "simply using gorilla/context should suffice" in the context of Writing Per-Handler Middleware.
But if it's request bound... err.. syntax error, does not compute. If a duck floats on water then witches are made from wood. And because ducks also float on water if her weight is the same as that of a duck she must be a witch. Or something like that ;)
And how could this be useful as a middleware "manager" when it's request-bound, I can't set it globally. Could you perhaps show an example of how a gorilla/sessions could be used with gorilla/context?
As the person who asked that other question:
gorilla/context allows you to store data in the request. If you have some middleware that does some pre-processing on a request before deciding to continue (i.e. anti-CSRF), you might want to store a token in the request so your handler can pass it to the template. The gorilla/context documentation explains it well:
... a router can set variables extracted from the URL and later application handlers can access those values, or it can be used to store sessions values to be saved at the end of a request. There are several others common uses.
You may also want to store data in the session: error messages from form submissions, a user ID, or the 'canonical' version of the CSRF token for that visitor will likely be stored here. If you try to store an error message in the request context, and then re-direct the user, you'll lose it (that's a new request).
So why would you use context over sessions? It's lighter, and allows you to de-couple parts of your application (often, HTTP middleware!) from each other.
Example:
Request comes in
CSRF middleware checks the session for an existing CSRF token. Does not exist, so it sets one.
It also passes this new token (via the request context!) to the handler that renders your form, so it can render it in the template (otherwise you would have to pull the token from the session again, which is wasted effort)
Request is done.
New request on form submission
The token still persists in the session, so we can compare it to the submitted token from the form.
If it checks out, we proceed to process the form
If not, we can save an error in the session (a flash message; i.e. one that is erased after reading) and re-direct.
This re-direction is a new request, and therefore we can't pass the error message via the request context here.
An example.
I'm writing this multi-community-forum software.
Now I have a gorilla/mux router that serves different content for the main domain and another router that serves different content filtered by subdomain.domain.tld.
Context is very useful here, else you would repeat yourself over and over again. So if I know that for the subdomain router every request would do string operations to find out the subdomain name and check if it exists in the database I could just do this here (in context) for every request and then store the subdomain name in a context variable.
And likewise if a forum's category slug or forum slug or a thread slug is set pass it to the handler, keep the processing that needs to be done in "context" and have less code in your handlers.
So the advantage of context is essentially to keep code DRY.
Like elihrar wrote, his example of a CSRF token. If you know that you need to check for the CSRF token on each request - don't duplicate this check in every handler that needs to do this, instead write a context wrapper ( / http.Handler) and do this for every request.

Hide GET parameters in a URL / rewrite to a clean URL / save GET params in SESSION?

I've looked around here but I can't find a matching solution to my problem here.
What I want to do is 1) clean up the URLs with GET params in them and 2) save those GET params in session variables.
This will also need to be done on all files on the site, so the GET params could get passed to any file on the server in any order.
So, for example, if one of the files is:
http://mydomain.com/page.php?a=1&b=2&c=3
and another is:
http://mydomain.com/anotherpage.php?b=2&a=1
I'd need those rewritten or redirected to /page.php and /anotherpage.php, respectively, while storing the GET params in session, so having $_SESSION['a'] = 1, etc.
I've managed to do this (kind of) by including a function called rewrite() in every file's header (before anything else) and going through all the variables in there, storing them in a session and then redirecting the file through header() to $_SERVER['SCRIPT_NAME'].
And it kinda works, but what I'm seeing now is issues with tracking scripts out there - when I try to integrate user tracking scripts I get errors because of a lot of redirects. Postbacks from other apps/websites are throwing 301/302 errors because of redirects as well.
So I was wondering is there a slicker method of just taking a QUERY_STRING for each called URL, storing all the key/value pairs from there in session cookies with key being the name of the session, value being the value of the session and just simply loading the clean SCRIPT_NAME instead without a possibility of endless redirection and all?
Thanks!

Azure ACS + Form value storage

I'm using Azure ACS in my ASP.net MVC 3 website (hosted in Azure too), the scenario is this:
A user first enters my website and fills a one field form, then they need to chose a provider and login, but first I want to store the field value so when they come back from login I'm able to create a profile with this value for the loged in user.
So I believe when they first enter the site and then leaves to login and enters the site again those are two different sessions am I right? and that's the reason the stored data using session state (through SQL Server) is not present when they come back after login am I right? if this is true what would be the best approach then? if not then I'm doing something wrong storing temp data right?
Thanks
UPDATE:
I have discovered that HttpContext.Application state works keeping the data, still I'm not sure if it's a good idea to use it in a controller considering it's in Azure, will it work on production properly??
You can pass state around in the WS-Federation redirect sequence using the wctx URL parameter. In the action that handles the initial POST request, you should get hold of the form parameter you want to keep, then redirect to you identity provider selection page (this will have to be a custom page) with the form parameter appended to the URL. When the user selects an IP on your page, you can pass the parameter on again using the wctx parameter. The WS-Federation passive requestor profile says that this should be returned to you eventually when the IP redirects the user back to your site.
This has some details
http://msdn.microsoft.com/en-us/library/bb608217.aspx
Edit: To get the wctx parameter out of the request when the user finally comes back to your app. Put something like this in the action code:
var fam = FederatedAuthentication.WSFederationAuthenticationModule;
if (fam.CanReadSignInResponse(System.Web.HttpContext.Current.Request, true))
{
string wctxValue = this.HttpContext.Request.Form["wctx"];
}
My preference is to have the wcxt parameter represent a redirect URL (URL encoded) with your parameter as a query parameter in that so it be a URL encoded version of this:
wctx=https://yourserver/yourapp/yourpage?yourparameter=foo
Then the action that was receiving the redirect from the ACS would simply pull out the value of wctx and do a redirect to it without any more processing. This keeps things simple.
Another approach would be to save whatever data you need to pass around in the Database, and just pass around some ID that refers back to the database record. You'll pass this ID to IP and back through wctx (as Mike mentioned above).
This will solve the issue of limited length of URLs (in case your data is very large). Of course you would need to manage deletion of this data, but this shouldn't be hard.

Redirect CI problem

I'm kind of new with CodeIgniter and I'm still learning (a lot).
So I have a view and when I submit a form I 'call' the controller by surfing to the right URL dynamically e.g. site/delete
class Site extends Controller {
function index(){$this->load->view('...')}
function delete() {
$this->site_model->delete_row();
$this->index();
}
}
Now when that action is done (deleted the row) I'm calling $this->index(); to redirect to my initial page (which is good) but my url stays: site/delete . I want my URL to be ../site/index (or without the /index)
Any help would be appreciated :-) .
So far I found something to solve this:
instead of:
$this->index();
I'm using:
redirect('site');
Does anyone know this is a good practice?
Redirect is what you should use.
In the user guide:
http://codeigniter.com/user_guide/helpers/url_helper.html
they use it after checking if a user is logged in. Depending on if they are or not, they redirect to a different place.
Also, note that any code after the redirect won't run. Make sure and redirect after you've done everything you need to.
My preferred method is to have actions like that handled by the same method that will be seen by the user afterwards.
What if you go to /site/delete afterwards, as a user? It will either have to detect and throw a error (show a message) or redirect to an appropriate page. /site/delete has no meaning.
For example, if a user would normally see an overview after deleting, then my form will be posted to /site/index; with index quickly checking for the condition and calling _delete() in the same controller, before doing its normal work.
That way, if the user refreshes the page, or presses 'back', things should look consistent to them.
Another example would be that /settings/edit would post to itself - this means that it can act on the post and show any output (e.g. validation errors). It means there's no /settings/do_edit location on my site, and also means that the user can go back to /settings/edit safely, and see a form for editing their settings.
I suppose this is a subjective take on a perhaps objective question, and I would encourage feedback on my view, but it's my way of avoiding the problem you have asked about.
$this->index();
Call of function in a function simply execute the functionality within that function.
And url never changed.
for changing the url you should use.
redirect ( base_url().'site');
but you should load url helper in constructor.

Resources