Call .py file in ajax - ajax

Is it possible call below xmlrpc.py with ajax?
In terminal work fine after call
my#ubuntu:~/custom_module/xml_rpc$ python xmlrpc.py
import xmlrpclib
username = 'admin'
pwd = 'admin'
dbname = 'db_1'
sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)
sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')
partner = {
'name': 'User 1'
}
contact_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])

Related

strapi reset password alwasy call localhost

I configured template to use URL to send reset password email.
I alwasy got this email with link to localhost so on the server it does not work.
I checked the implementation and seems there this is no way to override it:
const url = `${getAbsoluteAdminUrl(
strapi.config
)}/auth/reset-password?code=${resetPasswordToken}`;
return strapi
.plugin('email')
.service('email')
.sendTemplatedEmail(
{
to: user.email,
from: strapi.config.get('admin.forgotPassword.from'),
replyTo: strapi.config.get('admin.forgotPassword.replyTo'),
},
strapi.config.get('admin.forgotPassword.emailTemplate'),
{
url,
user: _.pick(user, ['email', 'firstname', 'lastname', 'username']),
}
)
.catch(err => {
// log error server side but do not disclose it to the user to avoid leaking informations
strapi.log.error(err);
});
};
and
const getAbsoluteUrl = adminOrServer => (config, forAdminBuild = false) => {
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
let url = adminOrServer === 'server' ? serverUrl : adminUrl;
if (url.startsWith('http')) {
return url;
}
let hostname =
config.get('environment') === 'development' &&
['127.0.0.1', '0.0.0.0'].includes(config.get('server.host'))
? 'localhost'
: config.get('server.host');
return `http://${hostname}:${config.get('server.port')}${url}`;
};
The url can be set from the admin panel: General > Settings > Users & Permissions > Advanced settings > Reset password page.
You can use https://www.npmjs.com/package/strapi-plugin-config-sync to sync this across your environments.

i can't return a response value on my cypress api call

I'm trying to make a cypress api call and get the value to be use on a next stage api call and when i make a return it just send me a big obj of commands
the call im making is
Cypress.Commands.add('getSession', () => {
cy.request({
method: 'POST',
url: `${Cypress.env('apiURL')}/New`,
headers: {
'Client-Type': 'backend'
}
})
.its('body')
.then(json => {
return {
id: json.value.props.id,
name: json.value.props.name
}
})
})
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
const session = cy.getSession()
cy.log('api respond', session.id)
cy.createMember(email, password, session.id)
})
and the response im getting is
[$Chainer] with a big obj
I'm not sure if the return on .then put it on a container but i can't find the value any when if someone can suggest what i have made wrong on the request call, that will be helpful
From the cypress docs:
So the createNew command must be rewritten to respect the async nature of cy commands.
Using then
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
cy.getSession().then( session => {
cy.log('api respond', session.id)
cy.createMember(email, password, session.id)
})
})
Using aliases
Cypress.Commands.add('createNew', (email = Cypress.env('userEmail'), password = Cypress.env('userPassword')) => {
cy.getSession().as("session")
cy.get("#session").then(session => {
cy.log('api respond', session.id)
})
cy.get("#session").then(session => {
cy.createMember(email, password, session.id)
})

AngularFireAuthGuard redirectUrl after login

I use firebase and AngularFireAuthGuard to protect specific routes, so that only authenticated users are allowed to access them.
In particular, my MainComponent and MgmtComponent should only be accessible to AUTHENTICATED users.
const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['/login']);
const routes: Routes = [
{ path: 'teams/:teamId/sessions/:sessionId',
component: MainComponent,
canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectUnauthorizedToLogin }
},
{ path: 'mgmt',
component: MgmtComponent,
canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectUnauthorizedToLogin }
},
{
path: 'login',
component: LoginComponent
}
];
My Problem is, that the user is not redirected back to the originally requested URL, after a successful login.
So what I want/expect is:
user goes to /mgmt
as the user is not authenticated he is automatically redirected to /login
user authenticates (e.g. via google or Facebook OAuth)
user is automatically redirected back to the originally requested page (/mgmt)
Steps 1-3 work fine, but step 4 is missing.
Now that the feature request is in, you can do this using the auth guard. However, the docs are unclear, so here is how I did it.
/** add redirect URL to login */
const redirectUnauthorizedToLogin = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
return redirectUnauthorizedTo(`/login?redirectTo=${state.url}`);
};
/** Uses the redirectTo query parameter if available to redirect logged in users, or defaults to '/' */
const redirectLoggedInToPreviousPage = (next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
let redirectUrl = '/';
try {
const redirectToUrl = new URL(state.url, location.origin);
const params = new URLSearchParams(redirectToUrl.search);
redirectUrl = params.get('redirectTo') || '/';
} catch (err) {
// invalid URL
}
return redirectLoggedInTo(redirectUrl);
};
This is an open feature request, the angularfire team is working on it: https://github.com/angular/angularfire/pull/2448
Meanwhile I found this workaround:
In the app-routing-module.ts instead of
const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['/login']);
I use following to store the url in the sessionStorage:
const redirectUnauthorizedToLogin = (route: ActivatedRouteSnapshot) => {
const path = route.pathFromRoot.map(v => v.url.map(segment => segment.toString()).join('/')).join('/');
return pipe(
loggedIn,
tap((isLoggedIn) => {
if (!isLoggedIn) {
console.log('Saving afterLogin path', path);
sessionStorage.setItem('afterLogin', path);
}
}),
map(loggedIn => loggedIn || ['/login'])
);
};
In the LoginComponent I read the value from the session storage to redirect:
sessionStorage.getItem('afterLogin');
this.router.navigateByUrl(redirectUrl);

How to pass 2 variables using json dumps to an ajax function?

I want to pass two variable: scenario_name and scenario_id from my view to my ajax function in the html code.
So basically in the database, each Organization can have multiple scenarios. The organization and scenario models have 2 fields each: an id field and a name field.
And my other doubt is, once I pass it to ajax, how do I access the variables passed?
my views.py
from django.shortcuts import render, redirect
from Organization.models import Organization
from django.http import HttpResponse
from Scenario.models import Scenario
import json
from django.core import serializers
def alertindex(request):
return render(request, 'alertindex.html', {
'Organization': Organization.objects.all(),
})
def get_scenario(request):
org_id = request.GET.get('org_id')
organization = Organization.objects.get(pk=int(org_id))
scenario = organization.scenario_set.all()
scenarios = serializers.serialize("json", scenario)
return scenarios
urls.py
from . import views
from django.conf.urls import url
urlpatterns = [
# Add alert url
url(r'^$', views.alertindex, name='alertindex'),
# Bind data in scenario drop down
url(r'^/Scenario$', views.get_scenario, name='Get_Scenario'),
]
my ajax function
var orgID = $(this).val();
var scenarios = '{{ scenarios }}'
$.ajax({
type: "GET",
url: "{% url 'Get_Scenario' %}",
data: { org_id: orgID},
success: function () {
var udata = "";
for (var i = 0; i < scenarios.length; i++) {
udata = udata + "<option value='"+ scenarios[i].scenario_id + "'>" + scenarios[i].scenario_name + "</option>"
$("#txtScenario").append(udata);
}
},
});
The url Get_Scenario links me to my view having the function get_scenario.
The error that I am facing is " str' object has no attribute 'get' "
Traceback:
File "/Users/anirudhchakravarthy/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/anirudhchakravarthy/anaconda3/lib/python3.6/site-packages/django/utils/deprecation.py", line 97, in call
response = self.process_response(request, response)
File "/Users/anirudhchakravarthy/anaconda3/lib/python3.6/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'
Any help will be greatly appreciated.
You can use JsonResponse. Here's sample code.
(It's better to check try/exception and send 404 when not found object)
from django.http import JsonResponse
def get_scenario(request):
org_id = request.GET.get('org_id')
# you can do your own validation
try:
organization = Organization.objects.get(pk=int(org_id))
scenario = organization.scenario_set.all()
scenarios = serializers.serialize("json", scenario)
except ObjectDoesNotExist:
data = {
'result': 'fail',
}
return JsonResponse(status=404, data)
data = {
"scenarios": scenarios,
# add more data you want
}
return JsonResponse(data)
For more information about JsonResponse, just check here

Cannot connect Ember Simple Auth and DRF Token Auth

I have a trouble with Ember Simple Auth.
I'm trying to connect my server-side application, which working on Django 1.9 with DRF, and client-side which working on Ember 2.2.
On server side I'm obtaining token on 'http://localhost:8000/api-token-auth/'. Function requires two args from request: "username" and "password". But Ember Simple Auth send POST request with args: "username[identification]" and "password[password]", and server returns "400". I think that problem with arguments keys.
POST request
Responce
I tried to change .authenticate method in oauth2-password-grant.js(i can't write custom authenticator because i'm newbee in javascript), but nothing changed.
Manually POST request returns expected answer.
Please tell me the way to solve this problem.
And please forgive me for my english.
authenticate(identification, password, scope = []) {
return new RSVP.Promise((resolve, reject) => {
const data = { 'grant_type': 'password', username: identification, password };
const serverTokenEndpoint = this.get('serverTokenEndpoint');
const scopesString = Ember.makeArray(scope).join(' ');
if (!Ember.isEmpty(scopesString)) {
data.scope = scopesString;
}
this.makeRequest(serverTokenEndpoint, data).then((response) => {
run(() => {
const expiresAt = this._absolutizeExpirationTime(response['expires_in']);
this._scheduleAccessTokenRefresh(response['expires_in'], expiresAt, response['refresh_token']);
if (!isEmpty(expiresAt)) {
response = Ember.merge(response, { 'expires_at': expiresAt });
}
resolve(response);
});
}, (xhr) => {
run(null, reject, xhr.responseJSON || xhr.responseText);
});
});
},
My variant:
const data = { 'grant_type': 'password', 'username': identification, 'password': password };
authenticate: function () {
// var username = this.getProperties('username');
// var password = this.getProperties('password');
const {username, password} = this.getProperties('username', 'password');
this.get('session').authenticate('authenticator:oauth2', username, password).catch((reason) => {
this.set('errorMessage', reason.error || reason);
});
}
It was my mistake.

Resources