How to set locale with Grape API / Rails - ruby-on-rails-6

I have a Rails 6 app and a related API with grape.
I want to set locale the same way.
In my routes :
scope '(:locale)', locale: /#{I18n.available_locales.join("|")}/ do
mount MyApi::Api => '/api'
resources :users
# [....]
root to: 'home#index'
In my application, I update locale in application controller.
def set_locale
I18n.locale = extract_locale || I18n.default_locale
end
def extract_locale
parsed_locale = params[:locale]
I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
def default_url_options
{ locale: I18n.locale }
end
I don't know how to update locale in my Api (locale is not in params).

Related

Rspec test cookie value always nil

guys! I'm facing a problem (rails 7.0.4) I need to test a controller's method called set_locale. It sets a cookie[:locale] with one of these values: :en, :pt-BR, sets the locale with cookies[:locale] value and then redirects to the current page translated with the chosen language. Everything is working fine when using the app but I can't write a good test. This is the LocalesController:
class LocalesController < ApplicationController
before_action :set_locale
def default_locale_option
cookies.delete(:locale)
cookies.permanent[:locale] = I18n.default_locale # save cookies with default language
end
def set_locale
if params[:locale].present?
if params[:locale] == 'default'
default_locale_option
else
cookies.permanent[:locale] = params[:locale] # save cookies
end
end
locale = cookies[:locale]&.to_sym # this reads cookies
if I18n.available_locales.include?(locale)
I18n.locale = locale # use cookies locale
redirect_to request.referrer # to the same page
end
end
end
This is the test that I wrote. I'm trying to pass the value :en but it says : "expected: :en got: nil". I'm new in testing stuff...any idea?
require 'rails_helper'
RSpec.describe "Locales", type: :request do
describe "GET /set_locale" do
it "returns http found" do
get set_locale_path
expect(response).to have_http_status(:found)
end
end
describe "check language switch" do
it "should change the language from pt_BR to English" do
#pt-Br is the default language in I18n
get set_locale_path, params: {locale: :en}
expect(cookies[:locale]&.to_sym).to eq(:en)
end
end
end
Thanks in advance!

iOS WKWebView error: "localized string not found"

An application has been written using WKWebView.
Everything works fine on a test server. Moved the web part to the customer's server. Immediately when trying to load the first page, an error occurred in didFailProvisionalNavigation.
"didFailProvisionalNavigation", "Error Domain=WKErrorDomain Code=13 "localized string not found" UserInfo={_WKRecoveryAttempterErrorKey=<WKReloadFrameErrorRecoveryAttempter: 0x2807a4020>, NSErrorFailingURLStringKey=https://XXXXXX, NSErrorFailingURLKey=https://XXXXXX, NSLocalizedDescription=localized string not found}"
The application defines the localizations Base, English (en) and Russian (ru).
Everything works fine on the old server.
Old test server:
DB - Oracle 10.2.0.4
HTTP Server - OHS - 11
OS - WS2012R2
New broken server:
DB - Oracle 11.2.0.4
OHS - 12.1.3.0.0
OS - Windows Server 2008 R2 Enterprise
WKWebView settings:
let configuration = WKWebViewConfiguration()
configuration.preferences.javaScriptEnabled = true
configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
configuration.ignoresViewportScaleLimits = false
configuration.allowsInlineMediaPlayback = true
if #available (iOS 14.0, *) {
configuration.defaultWebpagePreferences.allowsContentJavaScript = true
configuration.limitsNavigationsToAppBoundDomains = true
}
webView = WKWebView(frame: .zero, configuration: configuration)
pullControl.attributedTitle = NSMutableAttributedString(string: "Pull to update"). setColor(.black)
pullControl.addTarget (self, action: #selector(pullAction (_ :)), for: .valueChanged)
if #available (iOS 10.0, *) {
webView.scrollView.refreshControl = pullControl
} else {
webView.scrollView.addSubview (pullControl)
webView.scrollView.bounces = true
}
webView.customUserAgent = "XXXXX iOS application"
webView.allowsBackForwardNavigationGestures = true
webView.scrollView.bounces = true
webView.navigationDelegate = self
webView.uiDelegate = self
let urlRequest = URLRequest(url: URL (string: SITE_URL)!)
webView.load(urlRequest)

Can't access faraday params on views

I have an API which has a database and another rails APP without active record, I'm also using ActiveResource to manage some db queries
My Front-end app controller is
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
skip_before_action :verify_authenticity_token
end
and i have an action to authenticate user from my front end to the API
from the front-end i have this method
def create_session
conn = Faraday.new(:url => 'http://localhost:3001')
conn.post '/auth_user', { :email => params[:email], :password => params[:password] }
end
and on API
def auth_user
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
conn = Faraday.new(:url => 'http://localhost:3000')
conn.post '/add_session', { :status => "right", :user => user.id }
else
conn = Faraday.new(:url => 'http://localhost:3000')
conn.post '/add_session', { :status => "wrong" }
end
end
Note that i have access to params[:email] and params[:password] and i get the right status to the front end
Then inside the front end i cannot access params[:status] or params[:user] excpet on byebug
i tried to do session[:user_id] = params[:user] and it's not working
what am i missing here ?
After some googling and playing around, I found out that i was doing it the wrong way.
Because the action has been executed and all it's variable has gone -As far as i could understand- so i managed to get this info by executing:
conn.get '/auth_user'
Then i could receive a response with json info which i need.

Nexus3 Groovy script to add role using External Role mapping from LDAP

I'm working with Nexus3 groovy scripting to Provision/Bootstrap my Nexus3 - OSS instance. While looking through the complex scripting examples and the shell scripting examples as well as the sonatype books, i'm not seeing any clear documentation about the security method and it's parameters.
My main question is how do I map an LDAP group to a Nexus Role using groovy?
security.addRole('admin.role', 'Admin', 'Some Description', 'nx-admin', 'LDAPGroupName')
I'm getting a 400 with this when pushing to Nexus and running. I appreciate any help I can get here.
I think, it's bit a late update.
It seems , you are passing up the wrong parameter type for privilege and role.
I'd suggest you try below :-
security.addRole('admin.role', 'Admin', 'Some Description', ['nx-admin'], ['LDAPGroupName'])
The script below adds mapping from LDAP role to nexus role.
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.sonatype.nexus.security.SecuritySystem
def request = new JsonSlurper().parseText(args)
String ldap = request.ldap
String name = request.name ?: request.ldap
String nexus = request.nexus
assert ldap != null && nexus != null
def role = security.addRole(ldap, name, "Mapping for LDAP "+ldap, [], [nexus]);
JsonOutput.prettyPrint(JsonOutput.toJson(role))
The parameter 'ldap' is LDAP role name and 'nexus' is nexus role name (like 'nx-admin'). Note after adding mapping two roles with the same id will appear (one for LDAP source, other for default). Nexus apparently correlate them by id. Script below lists all roles (LDAP and default one). You might need to pass user LDAP user name to this script in order to LDAP roles to appear, because LDAP is deactivated if it is not used for some time, in that case script will show only nexus roles.
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.sonatype.nexus.security.SecuritySystem
SecuritySystem securitySystem = container.lookup(SecuritySystem.class.name)
if(args != null && args.length() > 0) {
def request = new JsonSlurper().parseText(args)
if(request.user != null && request.user.length() > 0) {
securitySystem.getUser(request.user)
}
}
JsonOutput.prettyPrint(JsonOutput.toJson(securitySystem.listRoles()))

Channel.Security.Error...Error #2048

I recently upgraded to Flash Builder 4.5 for PHP and am trying to upload a release build to my remoteserver. When I try to make a php call from the app, I get the error:
Send failednChannel.Security.Error error Error #2048 url: 'http://localhost/my_php/public/gateway.php'
The release build works fine on my localhost machine. All of my php service calls are on my remote host. Here's the structure of my remote host:
/my_directory/html (this is the root directory)
/my_directory/html/my_php/public/release (this is where my .html wrapper and .swf files sit)
/my_directory/html/my_php/public (this is where my gateway.php and amf_config.ini files sit)
The error specifically references 'localhost', but I can't find where that gets set. When I google error #2048, the solutions point to a badly configured crossdomain file...all my services are on remotehost (where the app is hosted) so I don't think that could be the issue.
Here is my amf_config.ini file:
[zend]
webroot = "/my_directory/html"
zend_path ="/my_directory/html/ZendFramework/library"
library ="/my_directory/html/my_php/library"
services ="/my_directory/html/my_php/services"
[zendamf]
amf.production = false
amf.directories[]=/my_directory/html/my_php/services
Here is my gateway.php file:
<?php
ini_set("display_errors", 1);
$dir = dirname(__FILE__);
$webroot = $_SERVER['DOCUMENT_ROOT'];
$configfile = "$dir/amf_config.ini";
$servicesdir = $dir.'/../services';
$librarydir = $dir.'/../library';
//default zend install directory
$zenddir = $webroot.'/ZendFramework/library';
//Load ini file and locate zend directory
if (file_exists($configfile)) {
$arr = parse_ini_file($configfile, true);
if (isset($arr['zend']['webroot'])) {
$webroot = $arr['zend']['webroot'];
$zenddir = $webroot.'/ZendFramework/library';
}
if (isset($arr['zend']['zend_path'])) {
$zenddir = $arr['zend']['zend_path'];
}
if (isset($arr['zend']['library'])) {
$librarydir = $arr['zend']['library'];
}
if (isset($arr['zend']['services'])) {
$servicesdir = $arr['zend']['services'];
}
}
// Setup include path
// add zend directory, library and services to include path
set_include_path(get_include_path()
.PATH_SEPARATOR.$zenddir
.PATH_SEPARATOR.$librarydir
.PATH_SEPARATOR.$servicesdir);
// Initialize Zend Framework loader
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true)->suppressNotFoundWarnings(true);
// Load configuration
$default_config = new Zend_Config(array("production" => false), true);
$default_config->merge(new Zend_Config_Ini($configfile, 'zendamf'));
$default_config->setReadOnly();
$amf = $default_config->amf;
// Store configuration in the registry
Zend_Registry::set("amf-config", $amf);
// Initialize AMF Server
$server = new Zend_Amf_Server();
$server->setProduction($amf->production);
if (isset($amf->directories)) {
$dirs = $amf->directories->toArray();
foreach ($dirs as $dir) {
if ($dir == "./") {
$server->addDirectory($webroot);
} else
if (realpath("{$webroot}/{$dir}")) {
$server->addDirectory("{$webroot}/{$dir}");
} else
if (realpath($dir)) {
$server->addDirectory(realpath($dir));
}
}
}
// Initialize introspector for non-production
if (! $amf->production) {
$server->setClass('Zend_Amf_Adobe_Introspector', '',
array("config" => $default_config, "server" => $server));
$server->setClass('Zend_Amf_Adobe_DbInspector', '',
array("config" => $default_config, "server" => $server));
}
// Handle request
echo $server->handle();
i had the same problem in a flex - blaze - environment. The real Problem was the context-root in the project properties.
because you used flex 4.5, there is no input field for this setting. in flex builder 3, there was a setting in the project properties -> flex server -> context root.
i gone crazy and found after hours an article on adobes bugs-site [FB-22939].
That solve my problem. I have no idea, wich project settings you are using, try to search a string named {context.root} in your project or post a liite bit more about your project settings. i know blaze is different from php, but maybe it is a tip bringing you back on track.
Unfortunately I'm not able to reproduce my thread and setting up an php environment with more knowledge about your setup. (Server-Technology, and so one)
edit:
additional Info:
I've found a list of all compiler arguments. Try it with this argument:
-context-root <context-path>
full name -compiler.context-root
path to replace {context.root} tokens for service channel endpoints
br
Frank

Resources