#StackBounty: #magento2 #rest How to expose a custom field from sales_order table to rest api ?

Bounty: 50

I have a custom field delivery_type in sales_order table. I am accessing order using rest api but this field is not present in response.

Requested api: http://localhost/default/rest/default/V1/orders/2

As suggested here I have added etc/api2.xml with following content in a custom module but it is not making any difference to order response.

<?xml version="1.0"?>
<config>
    <api2>
        <resources>
            <order>
                <attributes>
                    <delivery_type>Delivery Type</delivery_type>
                </attributes>
            </order>
        </resources>
    </api2>
</config>


Get this bounty!!!

#StackBounty: #authentication #rest #jwt #keychain Is it safe an stateless authorization mechanism where the clear password is stored o…

Bounty: 50

Is it safe to use the following stateless authorization mechanism between a client (iOS & Android) and server?

Sign up

  1. The client provides an email and password and saves the clear password on the Keychain of iOS and using some alternative for Android.

  2. The server checks the password strength if it’s deemed strong enough the user is created on DB.

  3. The server generates a JWT token and returns it to the client. The token has an expiration time of 15 minutes.

  4. The client stores the token (maybe on the Keychain itself) and includes it for each following request on the Authorization header.

  5. For each request, the server checks the token provided (checks the signature and the expiration time). If it’s ok the request is processed, otherwise, an HTTP 401 is returned.

Sign in

  1. When the client receives an HTTP 401 from the server it means a login is required. So the app accesses to the Keychain and gets the email & password and sends it to the server (no user intervention needed).
  2. The server validates the credentials provided and if they’re valid it will repeat the Sign Up steps from 3 to 5.

Thanks to expiration time on the token, if a token is compromised it will be valid during a short time period.

If a user is logged on multiple devices and she changes her password from one device, the other devices will keep logged only for a short time period, but the clear password stored on the Keychain will not be longer valid. So a new manual login will be required, which I think it’s fine.

Which drawbacks do you see?

I’ve been thinking on using refresh token procedure to avoid store the clear password but this adds complexity and other drawbacks (for example: how to guarantee the refresh token is only used once). And as far as I’ve seen, storing the clear password on the KeyChain is secure enough:

KeyChain Services Documentation

What is the best way to maintain the login credentials in iOS?

But I also have seen other questions that do not recommend storing passwords on the device.

So I would like to hear opinions from others on this.


Get this bounty!!!

#StackBounty: #php #rest #twitter #twitter-oauth PHP – Twitter API (OAuth) with pagination not working properly

Bounty: 50

I have integrated Twitter API (Twitter OAuth) to get latest feeds of particular company account and here below is my code what I have done so far (https://tomelliott.com/php/authenticating-twitter-feed-timeline-oauth).

<?php 
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library

$twitteruser = "CompanyName";
$notweets = 3;
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
    $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
    return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets);


?>


                                <?php foreach ($tweets as $current_tweet) { ?>
                                    
REGENCY CORPORATE

created_at; echo date("F d Y, H:i A", strtotime($date)); ?>

<?php $twitt_url = '#'; $twitter_target = ''; if (!empty($current_tweet->id)) { $twitt_url = 'https://twitter.com/' . $twitteruser . '/status/' . $current_tweet->id; $twitter_target = 'target="_blank"'; } ?> <a href="<?php echo $twitt_url; ?>" class="hovicon effect-5 news-icon" <?php echo $twitter_target; ?> > <i class="fa fa-twitter"></i> </a> </div> <p class="MontRegular themeFontGrey"> <?php echo $current_tweet->text; ?> </p> </div> <?php if (!empty($current_tweet->entities->media[0]->media_url)) { ?>
entities->media[0]->media_url; ?>" alt="Images" height="20%" width="20%" />
<?php } ?> <hr /> </div> <?php } ?>

This works well, I am getting 3 latest tweets. Now I want to add pagination into this, hence I followed documentation provided by Twitter (https://developer.twitter.com/en/docs/basics/cursoring.html), and below is my updated code with cursor for the same and I printed the array (response).

<?php 
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library

$twitteruser = "CompanyName";
$notweets = 3;
$cursor = -1;

$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
    $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
    return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);
echo '<pre>';
print_r($tweets);
exit;
?>

As you can see, here I have added $cursor = -1; and updated my api target url to $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);, passing cursor value.

Here I am getting the 3 recent tweets, however, as per mentioned in documentation from above link (https://developer.twitter.com/en/docs/basics/cursoring.html), you should get response like below.

{
    "ids": [
        385752029,
        602890434,
        ...
        333181469,
        333165023
    ],
    "next_cursor": 1374004777531007833,
    "next_cursor_str": "1374004777531007833",
    "previous_cursor": 0,
    "previous_cursor_str": "0"
}

I have also tried to update requested feed url to this.

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser .  "&cursor=" . $cursor);

But I am not getting any keys like next_cursor in any ways so far to be able to proceed. Can someone guide me, what I am doing wrong here, and what should I do to enable pagination from here on?

Any help or suggestion will be highly appreciated.

Thanks


Get this bounty!!!

#StackBounty: #magento2 #rest #section Section reload not working on specific REST request

Bounty: 100

I have created my custom section which reloads when cart data are updated.
For this I have created sections.xml file with below code.

<action name="rest/*/V1/carts/*/payment-information">
    <section name="mysection" />
</action>
<action name="rest/*/V1/carts/*/shipping-information">
    <section name="mysection"/>
</action>
<action name="rest/*/V1/carts/*/totals-information">
    <section name="mysection"/>
</action>

Here, my section gets successfully updated when first two requests are executed. rest/*/V1/carts/*/payment-information and rest/*/V1/carts/*/shipping-information
But its not refreshing my section data on last request which is rest/*/V1/carts/*/totals-information

I have checked that when rest/*/V1/carts/*/payment-information and rest/*/V1/carts/*/shipping-information is called, there is a call to reload section data but when rest/*/V1/carts/*/totals-information is called, there is no section reload request.

How can I fire a section reload request on rest/*/V1/carts/*/totals-information request.?


Get this bounty!!!

#StackBounty: #rest #access-rights REST API External user access

Bounty: 100

I’m currently trying to access a sharepoint site through the REST api using an external user from another organization.

The user has been added to the Site Members group with the Edit rights successfully. Tho, after retrieving an access token, I’m constantly getting this response:

GET https://<my-site>/_api/web # And all the other routes
{
  "error_description": "Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."
}

I allowed sharing on this site through the office 365 admin center but it seems like it’s impossible to access it anyway.

I’ve been searching for this on google for a few hours now and I still can’t get any results. I tried tweaking the settings in the Sharepoint admin center but nothing worked. Also, after going through the Sharepoint REST API documentation I couldn’t find anything about this particular use case.

Is it possible to access the REST API of a site using a user that is external to the organization itself?


Get this bounty!!!

#StackBounty: #mongodb #rest #iframe #rocket.chat Rocket.Chat REST API authentication when using "iframe auth"

Bounty: 50

I’m using the Rocket.Chat REST API for some automated user management. This was working great after I installed Rocket.Chat and my admin user had a username/password combo. Then, I activated the “iframe authentication” system in the admin panel. Now, when I try to use the REST API “login” endpoint, I get the error “User has no password set”. Any ideas why this is happening? When I look at the user document in the MongoDB for Rocket.Chat, there is no “password” field (seems to have been deleted when I activated the iframe authentication).

UPDATE: I disabled the “iframe authentication” system and set a new password on my account. Looking at the DB now, that user has a “password” entry, so the password is there. But, now I can’t log in because it says my password is incorrect. In summary, this software has a lot of bugs, it seems.


Get this bounty!!!

#StackBounty: #node.js #rest #file-upload #sftp NodeJS API sync uploaded files through SFTP

Bounty: 50

I have a NodeJS REST API which has endpoints for users to upload assets (mostly images). I distribute my assets through a CDN. How I do it right now is call my endpoint /assets/upload with a multipart form, the API creates the DB resource for the asset and then use SFTP to transfer the image to the CDN origin’s. Upon success I respond with the url of the uploaded asset.

I noticed that the most expensive operation for relatively small files is the connection to the origin through SFTP.

So my first question is:

1. Is it a bad idea to always keep the connection alive so that I can
always reuse it to sync my files.

My second question is:

2. Is it a bad idea to have my API handle the SFTP transfer to the CDN origin, should I consider having a CDN origin that could handle the HTTP request itself?


Get this bounty!!!

#StackBounty: #ruby-on-rails #json #rest #api-design #endpoint How can I output more data in my json endpoint?

Bounty: 50

I set up a simple json api endpoint for my Rails application. I have a model Item that belongs to another model List, and I want to display all the Items that belong to a particular List. However, only 606 Items are actually displayed before the json document abruptly ends. Is it possible to somehow specify that the endpoint display more data, or is that the limit?

def endpoint
  list = List.find_by(name: params[:list])
  respond_to do |format|
    format.html
    format.json {render json: list.items}
    # this list has thousands of items but only 606 are displayed.
  end
end


Get this bounty!!!

#StackBounty: #javascript #rest #redux #angular-2+ Angular+Redux app organization and initialization: transfer from a PHP-driven website

Bounty: 200

Our system is largely a PHP-driven system. We’re not doing the full split back/front-end. Most pages are plain HTML served directly by PHP. However, a few parts of the system are very dynamic and so are built with an Angular front-end.

A few relevant details:

  1. I wanted the transition from the PHP-driven website to the Angular app to be seamless for the user (i.e. they should not have to login again)
  2. Both PHP and Angular should be designed with the idea in mind of a future transition to a pure-Angular front-end. When that happens, I shouldn’t have to re-write the Angular app or the PHP backend.
  3. The Angular app uses redux
  4. The Angular app does not have to do any routing.
  5. This particular app manages rules and actions for a rules engine. The details are fairly complicated, but also not entirely relevant. My primary concern here is over how the Angular app is organized and initialized, regardless of what exactly the app is actually doing.

Regarding the transition from PHP to Angular: keeping in mind a future goal of a completely split back and front-end, I wanted my app to communicate exclusively with REST APIs, and not to be using the cookie that the rest of the PHP application uses to store details about the logged in user. As a result, I have a special PHP end point that authenticates the user via their cookie and returns an API token. That API token is then stored and used by the Angular app for all other API calls in a RESTful fashion. As a result, the actual “startup” procedures for the Angular app are:

  1. POST to login API and fetch API Token
  2. POST to various endpoints to fetch all the configuration data needed for the app to do its job
  3. Use that data to populate the Redux store

Starting with my App component, here is some more relevant background:

  1. The API URL for all of this is not fixed: this application is used to manage the Rules engine for a variety of different modules, and each module has its own API URL with slightly different configuration details but the exact same API mechanics. As a result, the API URL is not hard-coded. In the development environment the API URL comes out of the environment, and in production it is passed down from the PHP page that launches the angular app via a simple global variable that is pulled out of the window object.
  2. All the services here are my action creators for the redux store. The various calls to service.fetchY() all take the configuration (which contains the ApiUrl and ApiToken) and make their own API call, updating the Redux store with the results.
  3. app.component.html is relatively empty. It just contains a small skeleton and then defers everything to a couple sub-modules that have main components which get their data out of the Redux store. As a result, app.component doesn’t do much other than initializing the app. I’ve considered having it select different parts of the store to pass off to said sub-modules, but that will likely end up being the entire store, so I’d rather just let each sub-module pick out only the parts they need.

app.component.ts

import {
    Component,
    OnInit
} from '@angular/core';

import { select } from '@angular-redux/store';
import { IEnvironment } from './store/config/i-environment';
import { ConfigService } from './store/config/config.service';
import { RuleModelService } from './store/rule-model/rule-model.service';
import { FieldService } from './store/field/field.service';
import { PlaceHolderService } from './store/place-holder/place-holder.service';
import { WindowService } from './window.service';
import { environment } from '../environments/environment';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit{

    @select() ruleModels$;

    constructor(
        private configService: ConfigService,
        private uiService: UiService,
        private windowService: WindowService,
        private ruleModelService: RuleModelService,
        private fieldService: FieldService,
        private placeHolderService: PlaceHolderService
    ){}

    ngOnInit(){
        // this pretty much starts the whole app.
        // in production, we get the ApiUrl out of the window, because
        // it is set as a variable in a <script> tag.  Otherwise these
        // things come out of our environment
        let environmentData: IEnvironment = Object.assign({}, environment);
        if (environmentData.production){
            environmentData.ApiUrl = this.windowService.window().ApiUrl;
        }

        // configService.getConfig() will call the login endpoint and get the API Token.
        // This is actually stored in the Redux store, but rather than subscribing
        // to the config portion of the Redux store, I had the configService also return a
        // promise that returns the configuration.  I do this simply to make the connection
        // between that first API call and the subsequent initialization steps more obvious.
        this.configService.getConfig(environmentData).then((config) => {
            this.ruleModelService.fetchRuleModels(config);
            this.fieldService.fetchFields(config);
            this.placeHolderService.fetchPlaceHolders(config);
        });
    }
};

store/config/config.service.ts

import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { IConfig } from './i-config';
import { IEnvironment } from './i-environment';
import { IState } from '../i-state';
import { SET_CONFIG } from '../actions';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class ConfigService {
    constructor(
        private ngRedux: NgRedux<IState>,
        private http: Http
    ) { }

    getConfig(environment: IEnvironment): Promise<IConfig> {
        let ApiUrl = environment.ApiUrl;

        // initialize an HTTP request to get the user's login credentials
        let headers = new Headers({
            'Content-Type':     'application/json'
        });

        // our API key is actually fetched via an HTTP request that relies on cookie-based auth.
        // This isn't ideal, but it is a temporary hack that helps with logins as we transfer back and
        // forth between the PHP-driven system and the angular driven system.  It will go away
        // once we switch fully to a split back and front end, and it shouldn't introduce any
        // actual security risks.
        return new Promise<IConfig>( ( resolve: Function, reject: Function ): void => {
            // In the development environment these details are set in our environment
            if ( !environment.production ) {
                let config: IConfig = {
                    ApiUrl,
                    RuleId: null,
                    ApiKey: environment.ApiKey,
                    MembershipId: environment.MembershipId
                };

                // update the redux store and resolve our promise
                this.setConfig( config );
                resolve( config );
                return;
            }

            this.http
                .post( `${ApiUrl}?route=login`, '', { headers: headers } )
                .toPromise()
                .then( ( response ) => {

                    let auth = response.json().data;

                    // get the data we care about out of the results
                    let config: IConfig = {
                        ApiUrl,
                        RuleId: null,
                        ApiKey: auth.ApiKey,
                        MembershipId: auth.MembershipId,
                    };

                    // update the redux store and resolve our promise
                    this.setConfig( config );
                    resolve( config );
                } )
                .catch( ( error ) => {
                    reject( error )
                } );
        } );
    }

    setConfig( config: IConfig ) {
        this.ngRedux.dispatch<any>( { type: SET_CONFIG, config } );
    }
}

store/place-holder/place-holder.service.ts

RuleService, PlaceHolderService, and FieldService are all nearly identical: just slightly different endpoints and interfaces. As a result, I’m only going to include one for the sake of space:

import { NgRedux } from '@angular-redux/store';
import { Injectable } from '@angular/core';
import { IState } from '../i-state';
import { IPlaceHolder } from './i-place-holder';
import { IConfig } from '../config/i-config';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { SET_PLACE_HOLDERS } from '../actions';

@Injectable()
export class PlaceHolderService{
    constructor(
        private ngRedux: NgRedux<IState>,
        private http: Http
    ){}

    setPlaceHolders(placeHolders: IPlaceHolder[]){
        this.ngRedux.dispatch<any>({type: SET_PLACE_HOLDERS, placeHolders});
    }

    fetchPlaceHolders(config: IConfig): void{
        // initialize an HTTP request to get the full series data
        let headers = new Headers({
            'Content-Type': 'application/json',
            'MembershipId': config.MembershipId,
            'Authorization': 'Bearer ' + config.ApiKey
        });

        this.http
            .get(`${config.ApiUrl}?route=get_placeholders`, { headers: headers })
            .toPromise()
            .then((response) => {
                this.setPlaceHolders(response.json().data.map((incoming: any): IPlaceHolder => {
                    return {
                        name: incoming.name,
                        label: incoming.label,
                    }
                }));
            })
            .catch(this.handleError);
    }

    handleError(error: any): void{
        console.error(error);
    }
}

I’m interested in any and all feedback, but here are some particular questions I have:

  1. I’m especially interested in any feedback on my initialization procedures: I ask the configService to get the application config (which primarily means the authentication token) and then use the result of that to trigger a call to the other endpoints, fully initializing the app. Is that reasonable?
  2. I am calling 3 different endpoints to get all the data I need. I had considered wrapping this all up in one endpoint that returns three different pieces of information. That would certainly involve less server calls (which is good), but also seems like a poor Separation of Concerns for an API endpoint (which is bad). Thoughts?
  3. These HTTP calls are mixed up inside my action-creator services. This seemed pretty reasonable to me, but I’m new to Redux and thought others might disagree. Am I being crazy here?
  4. The fetch methods in all the services both return promises that they resolve with the answer, and also update the store with the new data. This is certainly redundant. Obviously updating the store is a requirement. I could ditch the promise to minimize duplication (and I feel like that would be more in line with typical application flow), but in this one particular case I like being able to have that direct connection between “get some stuff” and “then do some more stuff”. Is this a reasonable time to step outside of the norm?
  5. Is it reasonable to have a relatively empty app.component with most behavior being handled by some sub-modules that access the store directly? Or should I have the app.component fetch data out of the store and attach itself to the inputs and outputs of the other components that are exported by the sub-modules? These guys are fairly complicated, and there would be a lot of data flowing back and forth.


Get this bounty!!!