Restful HTTP API pattern - http

I am designing a Restful HTTP API and have a design question.
In my application users should be able to suggest item creations.
Then I can either approve or disapprove them.
I wonder what the best VERB+URL pattern for this would be.
Example 1:
POST|GET|PUT|DELETE /items
A user POST a new item and I can either PUT it to "approved" from "pending" or DELETE it.
Here I must use GET /items?status=approved to get all approved items and GET /items?status=pending to get all pending items. Perhaps GET /items would get me all the approved ones by default.
But I don't get how I can prevent users from PUTting it to approved state.
or
Example 2:
POST|GET|PUT|DELETE /item_creation_suggestions
A user POST a new item suggestion and I can either approve by DELETE:ting it and do a POST /items or just DELETE it.
Here /items and /item_creation_suggestions are two separate collections. I just have to delete the suggestions and create the items when approving.
This makes it simple to protect my app from unauthorized access. I can just protect my /items with authorization, while /item_creation_suggestions could be used by anyone.
But this doesn't seem very Restful?
The same goes for when users are suggesting items updates and deletions and I either approve or disapprove them.
I am very new at Restful design so all feedback and suggestions would be appreciated!

The first one sounds good.
POST /items should create a new item and probably return a 202 Accepted status.
GET /items should return all approved items.
GET /items?status=pending should return pending items to users with the right permission.
PUT /items/[id] with a request body that designates a new status to change the status.
DELETE /items/[id] to delete the item.
In the end you need to decide what makes the most sense for your API, but the above sounds generally reasonable.

I'd also strongly prefer the first setup.
But I don't get how I can prevent users from PUTting it to approved state.
Your application logic needs to prevent users from POST'ing items with the approved state, if they don't have permission to do this. REST is not just a 'dead storage', you can actually process the request and throw a 403 Forbidden in case the user did something wrong.
Access control is still important and doesn't go against 'restfulness'.

Related

Is there a way with Hasura to do a mutation based on the result of a query, within the same GraphQL call (Hasura transaction)?

I tried to search for an example but, I presume it's not doable. I am looking to hopefully be proven wrong or to find an official confirmation that it's not doable.
Before using Hasura, I was doing transactional SQL queries that ensured that data was kept consistent.
For example, I would like to create a password reset token if a user requests it, only if the user can be found using an email address. Right now, I have to do 2 queries:
Try to find a user with the specified email address
Insert and assign the token to this user id
In that case, it's not too bad, but now if I want to consume that token, I have to do 3 queries:
Find the valid token
Change the password to the user associated with that token
Delete the token
Obviously, if something goes wrong and the token is not deleted, this could be an issue - so I would be curious to see if there would be ways to merge these queries/mutations into transactions.
Sounds like supporting nested updates would solve this problem for you with the least amount of effort. We are working on a rfc for the feature and hope to start development soon. Please follow this Github issue on our community for future updates.
https://github.com/hasura/graphql-engine/issues/1573
This comment outlines the current scope of the proposed feature. The rfc will provide a more complete explanation.
https://github.com/hasura/graphql-engine/issues/1573#issuecomment-1338057350
You can apply changes to rows that you filter by certain criteria. Here is a sample mutation:
mutation PasswordUpdate($id: uuid!, $token: String!, $new_password: String!) {
update_user(
where: {id: {_eq: $id}, token: {_eq: $token}}
_set: {token: null, password: $new_password}
) {
affected_rows
}
}
That query deletes the token and sets a password for all users (hopefully just one) that have the token assigned.
After some research here is what I found:
For the first example:
Try to find a user with the specified email address
Insert and assign the token to this user id
There are no solutions for this today and as answered by #damel, there is an ongoing RFC to support nested mutations: https://github.com/hasura/graphql-engine/issues/1573#issuecomment-1338057350
Hopefully, this feature will be out soon, but in the meantime, for most cases, it's not such a big deal to have multiple queries as it is possible to catch errors on the first query.
For the second example:
Find the valid token
Change the password to the user associated with that token
Delete the token
When sending multiple mutations in the same query, Hasura treats them as a transaction as announced in 2020.
Of course, it would be nice to do this in the same query (similar to the first example) but since there is a transaction on the mutation, for this case it's still not a problem.
I am sure there are probably cases where this can become a problem but I am not exposed to them right now. Nevertheless, it would be great if the RFC makes it to production, giving more options to Hasura users.

Two wordpress database with same users

I want to have the same WordPress users in two different databases
For example, if a user registers on SiteA, then he can login to SiteB. And reverse.
Also i want create same cookie for both after login.
mywebsite.com/ (SiteA_DB)
mywebsite.com/blog/ (SiteB_DB)
I've never done this before and maybe Wordpress has hooks to archive this, but I prefer using mysql for such a trick.
You could try ..
.. using 'federated storage' ( https://stackoverflow.com/a/24532395/10362812 )This is my favorite, because you don't even have to share a database or even the mysql serverThe downside is, that it doesn't work with db cache and uses an additional connection.
.. creating a 'view' ( https://stackoverflow.com/a/1890165/10362812 )This should be possible when using the database-name in the query itself and it would be the simplest solution if it works. Downside: The 2 tables have to share the same mysql-server and have to be assigned to the same user as far as I know.
-- **Backup your database before trying!** --
DROP TABLE `second_database`.`wp_users`;
DROP TABLE `second_database`.`wp_usermeta`;
CREATE VIEW `second_database`.`wp_users` AS SELECT * FROM `first_database`.`wp_users`;
CREATE VIEW `second_database`.`wp_usermeta` AS SELECT * FROM `first_database`.`wp_usermeta`;
This should work, according to: Creating view across different databases
.. creating a 'shadow copy' ( https://stackoverflow.com/a/1890166/10362812 )Works with caching and is a standalone tableDownsides as 2. solution + a bit of setup and I think it might be the worst option in performance
This were answers to this question: How do I create a table alias in MySQL
I merged them together for you and made them fit your use-case.
Please also notice, that solution 1 and 2 will replace your current user-tables auf "second_database" because you write directly into "first_database" when querying the fed. storage or the view. This can lead to problems with user-role plugins. You should take care of syncing the plugin-options too, if you should use one of them and in case it uses different tables or 'wp_options' values.
Let me know if this works, I have to do a similar task next week. While researching I found the linked answers.
EDIT: I was missing the point of "cookie-sharing" in my answer. Your example shows a blog on the same domain - you should be able to change the way wordpress sets its cookies to be domain-wide. What I did once for 2 different domains was, that I hooked into the backend (is_admin) and added a javascript which did a post-request to siteB, receiving a token which is stored but marked as 'invalid' on siteB. This token then was passed back to my plugin on siteA which checked if the user is logged_in and (in my case) have adminrights (current_user_can()) and if so, it was sending this token back to sideB which was marking this token as valid to login. (Make sure only sideA can tell sideB to make this token valid!) Once a user is seen with this token in a cookie on siteB, the user is logged-in automatically in the background. Also I made this bidirectional. I am sorry, that I can't share the code for you. I don't have access to it anymore.
Greetings, Eric!

Paypal Processing - Need to grab TransactionId, CorrelationId and TimeStamp

Current Project:
ASP.NET 4.5.2
MVC 5
PayPal API
I am using this example to build myself a PayPal transaction (and yes, my code is virtually identical), as I do not know of any other method that will return the three values in the title.
My main problem is that, the example I am utilizing is much more concise and compact than the one I used for a much older Web Forms application, and as such, I am unsure as to where or even how to grab the three values I need.
My initial thought was to do so right after the ACK, and indeed I was able to obtain the CorrelationId as well as the TimeStamp, but because this was prior to the user being carted off to PayPal’s site (sandbox in this case -- see the return new PayPalRedirect contained within the if), the TransactionId was blank. And in this example, PayPal explicitly redirects the user to a Success page without returning to the Action that sent the user to PayPal in the first place, and I am not seeing any GET values in the URL at all aside from the Token and the PayerId, much less ones that could provide me with the TransactionId.
Suggestions?
I have also looked at the following examples:
For ASP.NET Core, was unsure how to adapt to my current project particularly due to appsettings.json, but it looked quite well done. I really liked how the values were rolled up in lists.
For MVC 4, but I couldn’t find where ACK was being used to determine success or successwithwarning so I couldn’t hook into that.
I have also found the PayPal content to be like trying to drink from a fire hose at full blast -- not only was the content was hopelessly outdated (Web Forms code, FTW!) but there was also so many different examples it would have taken me days to determine which one was most appropriate to use.
Any assistance would be greatly appreciated.
Edit: my initial attempt at modifying the linked code has this portion:
values = Submit(values);
var ack = values["ACK"].ToLower();
if(ack == "success" || ack == "successwithwarning") {
using(_db = new ApplicationDbContext()) {
var updateOrder = await _db.Orders.FirstOrDefaultAsync(x => x.OrderId == order.OrderId);
if(updateOrder != null) {
updateOrder.OrderProcessed = false;
updateOrder.PayPalCorrelationId = values["CORRELATIONID"];
updateOrder.PayPalTransactionId = values["TRANSACTIONID"];
updateOrder.PayPalTimeStamp = values["TIMESTAMP"];
updateOrder.IPAddress = HttpContext.Current.Request.UserHostAddress;
_db.Entry(updateOrder).State = EntityState.Modified;
await _db.SaveChangesAsync();
}
}
return new PayPalRedirect {
Token = values["TOKEN"],
Url = $"https://{PayPalSettings.CgiDomain}/cgi-bin/webscr?cmd=_express-checkout&token={values["TOKEN"]}"
};
}
Everything within and including the using() is my added content. As I mentioned, the CorrelationId and the TimeStamp come through just fine, but I have yet to successfully obtain the TransactionId.
Edit 2:
More problems -- the transactions that are “successful” through the sandbox site (the ReturnUrl is getting called) aren’t reflecting properly on my Facilitator and Buyer accounts, even when I do payments straight from the buyer’s PayPal account (not using the Credit Card). I know I am supposed to see transactions in the Buyer’s account, either through the overall Dev account (Accounts -> Profile -> balance or Accounts -> Notifications) or through the Buyer’s account in the sandbox front end. And yet -- multiple transactions returning me to the ReturnUrl path, and yet no transactions in either.
Edit 3:
Okay, this is really, really weird. I have gone over all settings with a fine-toothed comb, and intentionally introduced errors to see where things should crap out. It turns out that the entire process goes swimmingly - except nothing shows up in my notifications and no amounts get moved between my different accounts (Facilitator and Buyer). It’s like all my transactions are going into /dev/null, yet the process is successful.
Edit 4: A hint!
In the sandbox, where Buyer accepts the transaction, there is a small note, “You will be able to review the transaction before completing it” or something like that -- suggesting that an additional page is not coming up and that the user is being uncerimoniously dumped back to the success page. Why the success page? No clue. But it’s happening.
It sounds like you are only doing the first part of the process.
Express Checkout consists of 3 API calls:
SetExpressCheckout
GetExpressCheckoutDetails
DoExpressCheckoutPayment
SEC generates a token, and then you redirect to PayPal where the user signs in and reviews the transactions before agreeing to pay.
They are then sent to the ReturnURL included in your SEC request, and this is where you'll call GECD in order to obtain all the buyer details that are now available since they signed in.
Using that data you can complete the final DECP request, which is what finalizes the procedure. No money is actually processed until this final call is completed successfully.

Create topic using a bot

I'm in a situation in which i need to be able to create a topics using self created bot. My forum has a special category and user, which can create a topics in that category.
Technology i'm using to create that bot is ruby + mechanize gem but it's not important right now. That bot works in a following way:
Sign in as previously mentioned user:
visit - /ucp.php?mode=login
fill the sign-in form using user credentials
if, after submiting a form, there is a sign-out link somewhere on the page, threat this whole process as "successfull"
Create a topic
visit - /posting.php?mode=post&f=21
fill subject field with desired subject
fill message field with desired message
submit a form using Submit button
And now, while first point works just great, the second one behaves in a strange way. After submiting a form, there is no error message or anything like that, i'm just getting redirected to /viewforum.php?f=21 (log's says that it's 302 Moved Temporarily status) page and the topic is not there.
Can anyone tell me what such behaviour means? Is there any security mechanism i don't know about? Please also note that the new topic form has form_token and creation_time fields filled correctly while form is beeing submited.
Thanks in advance for any clues.
According to this thread: https://stackoverflow.com/a/11713867/552936, user is treated as a bot if he sends a form without any delay (and it end's up with a 302 redirect). I can't find any info on google what's the exact delay, carck3r says that it's 8 seconds but for me, it was 2 seconds.

Page not found - show other possibles. Return 404 or 301?

If a users follows a dead link to my site and requests a record which is no longer valid I would like to be able to provide them with a list of other potential records which they might have been searching for. Most of my records get "soft" deleted so I am normally able to derive search data from the ID in the request - but never the new ID of the record (records can be moved but there is no link between the old a new records, other records may simply not exist any more).
My gut instinct is to return a page of content with the possible records along with a 404 header to hopefully get search engines to drop the index for that URL.
The other option would be to redirect (301 - or even 303??) to this results page.
I'd advocate a status code of 300 to indicate multiple choices (per RFC)
If you have one target to redirect to, use a 301 to redirect to it.
If you have multiple options, I would go with a 300 - it indicates multiple choices.
In my opinion you should go with the 404, since you stated you provide a list with multiple items. A redirect should be used with one possible item only.
update: I totally forgot about 300... use that one as mentioned before by Rowland Shaw
By "records" - do you mean vinyl?
For the "SEO" tag in your question - if you're running an eCommerce store and driving traffic keep the 200 OK and display the record as (permanently) out-of-stock (as you suggest) and offer alternate "records" - never drop an indexed product link for a "good" product.
I'd only advocate a "301 Permanent Redirect" if the product is genuinely damaging to your site / business.
For the "user-experience" - again keep the 200 OK - the user doesn't care what status is being returned.

Resources