iOS app - Rails 4 and Devise as backend - ios7

I would like to know how to use rails as backend for my iOS app.
All I need is a User with email and password to authenticate using devise.
I already have a User created with devise and rails 4.
I did find this post http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/ explaining what I need, but some things are still missing.
When I try to do a POST via my iOS app, I get the message "Can't verify CSRF token authenticity". How do I solve that without skipping the filter verify_authenticity_token ?
How would the request code for the iOS look like? Right now I'm doing a POST to http://localhost:3000/api/users/sign_in.json and setting the HTTPBody = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&jsonError], but the rails server is receiving only a string as key with the entire json dictionary, not an actual json dictionary.
params = {"{\"user\":{\"email\":\"qwe\",\"password\":\"123\"}}"=>nil, "action"=>"create", "controller"=>"api/sessions", "format"=>"json"}
How would I do an https request instead of http, so I can hide the password and email fields in case someone else tries to watch my internet traffic?
Thank you very much.

To use Rails Applications Mobile and Android and IOS, necessarily you have to use JSONP: example:
JS sample:
$.ajax({
url: '/api_mobile',
jsonp: "callback",
dataType: "jsonp",
cache: true,
data: {method: 'login', other_data ...},
success: function(res) {
// response object
console.log(res)
},
error: function(request, status, error) {
alert("Error server: " + request.status);
}
});
RAILS 4:
protect_from_forgery with: :exception, only: :api_mobile
# route /api_mobile
def api_mobile
json = {error: 'Not found Method'}
case params[:method]
when: 'login'
if User.login(params[:username], params[:password])
json = {notice: 'Login success'}
else
json = {error: 'Error Username or Password'}
end
end
render json: json, :callback => params[:callback]
end
All functions must be personalized and parameterized

Related

Facebook js api - "unsupported get request" error

I'm trying to get some (I think allowed) information in my app. I have an access token that has the following info:
App ID: <my app id> : iHOUSEListingPoster - Test 001
Type: User
App-Scoped User ID: <user id> : Joe Webb
Valid: True
Scopes: email, pages_show_list, pages_read_engagement, pages_manage_posts, public_profile
I'm trying this:
FB.api( "/me",
"GET",
{fields: 'name'},
function(get_fb_info_response) {
console.log("Here: ", get_fb_info_response
});
And getting this error:
"Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation"
I have tried with both "/me" and "/me/". And while I want name, picture and email, I tried limiting it to just name, and still. What am I missing here?
Try this:
FB.api('/me?fields=name', function(response) {
console.log('me', response);
});
I'm not sure if api function from FB does have this signature you're using.
Edit
After searching at Facebook docs, found that the signature you were using is valid as well. Then, I went to do some tests here. And I was able to reproduce the same error you have mentioned when calling the function like this:
FB.api("/<123>/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
To fix it, you need to remove < and >, for example:
FB.api("/123/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
Calling /me and /me/ endpoint returned no error in my test.
In this screenshot you can see the tests I have run directly at my browser's console.
Ok, I finally figured out what the problem is/was here (sheepish face). We have a couple of Facebook accounts here at the company. One is the container for my app and it's test app, the other is a more general company account. I was logged into the general company account. When I tried my app, it grabbed some random app from that account, which wasn't the app that matched the access token (which I think is possible wrong on Facebook's part), therefore this error was thrown.
Once I logged into the correct Facebook account, all works as expected.

No Host in request URL for Grafana datasource plugin tutorial - Add authentication

I'm trying to follow the example for developing a datasource plugin from Grafana. Ultimately I want my plugin to use Oauth, but even with just the basic Grafana datasource proxy example I seem to be having issues.
I have updated my plugin.json, class and constructor.
I have setup this hard coded example.
in plugin.json
{
"path": "grafana",
"url": "https://github.com"
}
],
And a sample testDataSource()
async testDatasource() {
return getBackendSrv()
.datasourceRequest({
url: this.url + '/grafana/grafana',
method: 'GET',
})
.then(response => {
if (response.status === 200) {
return { status: 'success', message: 'Data source is working', title: 'Success' };
} else {
return { status: 'failure', message: 'Data source is not working: ' + response.status, title: 'Failure' };
}
});
}
When I try and save/test this datasource to call that method, I get in the frontend a
HTTP Error Bad Gateway
And in the logs
t=2021-09-17T14:31:22+0000 lvl=eror msg="Data proxy error" logger=data-proxy-log userId=1 orgId=1 uname=admin path=/api/datasources/proxy/9/grafana/grafana remote_addr=172.17.0.1 referer=http://localhost:3000/datasources/edit/9/ error="http: proxy error: http: no Host in request URL"
I would've expected the request to be routed to the datasource proxy and for that to make the request to github but it seems Grafana is making a request to /api/datasources/proxy/9/grafana/grafana and nothing is picking it up?
Looking up my datasource via API, there's nothing listed for URL.
You will need to render this in your ConfigEditor.tsx
<DataSourceHttpSettings
defaultUrl="http://localhost:8080"
dataSourceConfig={options}
onChange={onOptionsChange}
/>
Which will give you the basic form with URL, whitelist, auth options that you see on most plugins. The URL there I guess should match what you have in your routes.

Ajax POST request not hitting Elixir router path

I have this redux-observable epic which does a POST ajax request using RxJS.ajax.post and I don't think it is hitting my Elixir router properly as nothing is happening on my elixir backend. I am doing get requests to get categories correctly and in the same manner so I am hitting other paths in my Elixir router correctly. I am expecting the issue to be with my backend Elixir code not my frontend. I might need to change my path in router.ex.
When I press a button on the frontend, this object is what gets sent to the elixir backend (it dispatches this action with a product as the payload and hits the redux-observable epic below):
onPress = {() => {
props.uploadProduct({
name: props.name,
brand: props.brand,
description: props.description,
image: props.image
})
The epic:
import { ajax } from 'rxjs/observable/dom/ajax'
import { Observable } from 'rxjs'
export const uploadProductEpic = action$ =>
action$.ofType(UPLOAD_PRODUCT)
.mergeMap(action => {
ajax.post('http://localhost:4000/products/', action.payload)
})
.map(response => uploadProductFulfilled(response))
.catch(error => Observable.of(
uploadProductRejected(error))
)
the elixir router:
defmodule Api.Router do
use Plug.Router
if Mix.env == :dev do
use Plug.Debugger
end
plug :match
plug :dispatch
get "/categories/" do
Api.Repo.getCategories(conn)
end
post "/products/:product" do
IO.puts inspect conn
Api.Repo.insertProduct(conn, product)
end
end
IO.puts inspect conn doesn't log anything. So My Elixir router path post "/products/:product" do is not being hit by my POST request. What am I doing wrong?
This is the elixir function in repo.ex that I HOPE will insert the product into my database:
def insertProduct(conn, product) do
product = %Api.Product{name: product.name, brand: product.brand, description: product.description, image: product.image, rating: 0, numberOfVotes: 0}
changeset = Api.Product.changeset(product)
errors = changeset.errors
valid = changeset.valid?
case insert(changeset) do
{:ok, product} ->
conn
|> put_resp_content_type("application/json")
|> send_resp(200, Poison.encode!(%{
successs: "success"
}))
{:error, changeset} ->
conn
|> put_resp_content_type("application/json")
|> send_resp(500, Poison.encode!(%{
failure: "Errors"
}))
end
end
I am a frontend developer just trying to get into Elixir so any guidance and patience is appreciated. Thanks.
Your data is sent in the body of the request, not in the URL, so the route should be:
post "/products"
You'll also need to plug in a JSON parser after plug :match and before plug :dispatch, as described in the Parameter Parsing section in the documentation of Plug.Router:
plug :match
plug Plug.Parsers, parsers: [:json],
pass: ["application/json"],
json_decoder: Poison
plug :dispatch
The JSON data will now be present in conn.body_params, which you can send to your function:
post "/products" do
Api.Repo.insertProduct(conn, conn.body_params)
end
And finally, the keys in the JSON would be strings, so you need to use the bracket syntax to access them instead of dots:
product = %Api.Product{name: product["name"], brand: product["brand"], description: product["description"], image: product["image"], rating: 0, numberOfVotes: 0}
I'm not sure how you've defined Api.Product.changeset, but the default Phoenix convention defines a 2 arity function which calls cast and extracts the data from a map itself. If you're doing the same, you can do this instead:
changeset = Api.Product.changeset(%Api.Product{}, product)

Use JSON request body rather than request parameters for Friend authentication in a Clojure Web Application

I am using Friend to build authentication into a Compojure web application.
I have defined a bespoke authentication workflow for Friend:
(defn authentication-workflow []
(routes
(GET "/logout" req
(friend/logout* {:status 200}))
(POST "/login" {{:keys [username password]} :params}
(if-let [user-record (authenticate-user username password)]
(workflows/make-auth user-record {:cemerick.friend/workflow :authorisation-workflow})
{:status 401}))))
The authentication part is factored out:
(defn authenticate-user [username password]
(if-let [user-record (get-user-for-username username)]
(if (creds/bcrypt-verify password (:password user-record))
(dissoc user-record :password))))
This works, but...
I am using AngularJS and having to post request parameters leads to some ugly Angular code (cribbed elsewhere from a StackOverflow answer):
$http({
method: 'POST',
url: '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: username,
password: password
}
});
I would much rather do this much simpler call instead and just post a JSON object via the request body:
$http.post('/login', {username: username, password: password})
I tried to use ":body" in the authentication handler instead of ":params" but the value of :body seemed neither JSON nor Clojure to me so I don't know how I can use it:
{username me#myapp.com, password password}
I already have JSON request/response mapping workflows working correctly for my REST API handlers, and I checked already that the request headers (e.g. ContentType) were correct for JSON.
So can this be done with Compojure/Friend, and if so how?
Here is some working code and an explanation...
First the Friend workflow, using the request body:
(defn authentication-workflow []
(routes
(GET "/logout" req
(friend/logout* {:status 200}))
(POST "/login" {body :body}
(if-let [user-record (authenticate-user body)]
(workflows/make-auth user-record {:cemerick.friend/workflow :authorisation-workflow})
{:status 401}))))
Second, the authentication function:
(defn authenticate-user [{username "username" password "password"}]
(if-let [user-record (get-user-for-username username)]
(if (creds/bcrypt-verify password (:password user-record))
(dissoc user-record :password))))
Third, the Compojure application with middlewares declared:
(def app
(-> (handler/site
(friend/authenticate app-routes
{:workflows [(authentication-workflow)]}))
(params/wrap-keyword-params)
(json/wrap-json-body)
(json/wrap-json-response {:pretty true})))
Finally a fragment of AngularJS code to post the credentials (username and password come from an AngularJS model):
$http.post('/login', {username: username, password: password});
So what happens is this...
The Angular javascript code posts JSON to the web application login URL. The "Content-Type" header is automatically set to "application/json" and the request body is automatically encoded as JSON, for example:
{"username":"batman#batcave.org","password":"tumblerrocks"}
On the server, the middleware parses the JSON to a Clojure map and presents it to the handler via the ":body" keyword:
{username batman#batcave.org, password tumblerrocks}
The request is then routed to the custom Friend authentication workflow.
Finally the submitted values are extracted from the Clojure map and used to authenticate the user.
I suspect that your wrappers are applied in the wrong order. Check that ring.middleware.json/wrap-json-body is applied before (outside of) the friend wrapper.
e.g.
(def my-handler (wrap-json-body (cemerick.friend/authenticate ...)))
Otherwise, a quick fix might be to just wrap your whole app in ring.middleware.json/wrap-json-params

OAuth Post Request Failing

I've got everything working up until Step 2 of the OAuth process where you request the actual token. I'm using a very simple jQuery Post request and constantly getting Access Control Origin errors. I've tried contentType: 'application/json' and everything else I know to try.
It's just not working and I'm not sure the problem. I've confirmed all the variables are set properly before the request. Simple post request...
var url = 'https://[STORENAMEVARIABLE].myshopify.com/admin/oauth/access_token';
var data = JSON.stringify({ client_id: apiKey, client_secret: secret, code: code });
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
debugger;
},
error: function(data) {
debugger;
}
});
Any ideas what I'm doing wrong?
You need to make your OAuth requests from a server. This is the Javascript cross-domain security kicking in.
If you are using Rails you can use omniAuth and it'll take care of the whole OAuth dance for you. Otherwise you'll have to search around but most popular language have an OAuth library that you can just plug in.