Trying to use this package: https://www.npmjs.com/package/passport-ldapauth
I managed to find the ldap-settings for my company in a medawikiserver (php)
$wgLDAPDomainNames = array("COMPANY");
$wgLDAPGroupBaseDNs = array("COMPANY"=>"dc=company,dc=se");
$wgLDAPAutoAuthDomain = "COMPANY";
$wgLDAPGroupUseFullDN = array("COMPANY"=>true );
$wgLDAPServerNames = array("COMPANY"=>"dcst.company.se");
$wgLDAPSearchStrings = array("COMPANY" => "COMPANY\\USER-NAME" );
$wgLDAPSearchAttributes = array("COMPANY"=>"sAMAccountName");
$wgLDAPBaseDNs = array("COMPANY"=>"dc=company,dc=se");
$wgLDAPEncryptionType = array("COMPANY" => "ssl" );
$wgMinimalPasswordLength = 1;
I need to map this to the node-package. I tried this:
var opts = {
server: {
url: 'ldaps://dcst.company.se',
bindDn: 'dc=company,dc=se',
//bindCredentials: 'secret',
searchBase: 'dc=company,dc=se',
searchFilter: '(&(objectcategory=person)(objectclass=user)(|(samaccountname={{username}})(mail={{username}})))',
searchAttributes: ['displayName', 'mail'],
}
};
I get "Bad request". This is from the docs:
badRequestMessage flash message for missing username/password (default: 'Missing credentials')
What have I done wrong?
You need to add the admin credentials. Here's how my configuration works:
var Strategy = require('passport-ldapauth').Strategy
, passport = require('passport')
, config = require('config')
, userLookup = require('./userLookup');
var ldapConfig = {
server: {
url: config.get('ldap.url'),
adminDn: config.get('ldap.adminDn'),
adminPassword: config.get('ldap.adminPassword'),
searchBase: config.get('ldap.searchBase'),
searchFilter: config.get('ldap.searchFilter')
}
};
passport.use('ldap', new Strategy(ldapConfig, userLookup));
Related
I am trying to query the database based on what the user has clicked on the page and display the data retrieved by it without refreshing the page. I am using Ajax for this. Let me show you the codes
html
<label for="landacq" class="civil-label">Land Acquisation Cases</label>
<input class="civil-category" type="radio" name="civil-cat" id="landacq" value="land acquisation" hidden>
<label for="sc" class="civil-label">Supreme Court</label>
<input class="civil-court" type="radio" name="civil-court" id="sc" value="supreme court" hidden>
<label for="limitation" class="civil-label">Limitation</label>
<input class="civil-law-type" type="radio" name="civil-law-type" id="limitation" value="limitation" hidden>
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (query) {
showCivilQ(query);
// console.log(data);
},
error: function (error) {
console.log(error);
},
});
});
}
function showCivilQ(query) {
q.textContent = query;
console.log(query);
}
So here for example, if the user the click the radio button in the html, the values are grabbed by in js file and then sent to the url mentioned as a POST request. There these values are use to filter the database and return the objects like this
views.py
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
return HttpResponse(query)
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
This is the result I am getting which is correct.
My Question is these objects contain attributes having some values in for eg, title, headnote etc. How can I display these attributes in the html rather than displaying the object names returned as shown in the Image like title of the citation, headnote of the citation etc
A solution could be to return a json object instead of the query resultset; because Ajax works well with json
You need a function that translates a Citation object into a dictionary (change it based on your real attributes). All elements must be translated into strings (see date example)
def citation_as_dict(item):
return {
"attribute1": item.attribute1,
"attribute2": item.attribute2,
"date1": item.date.strftime('%d/%m/%Y')
}
This dictionary must be translated into a json through import json package
def civil_home(request):
if request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
response_dict = [citation_as_dict(obj) for obj in query]
response_json = json.dumps({"data": response_dict})
return HttpResponse(response_json, content_type='application/json')
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
In your HTML page you should be able to parse the response as a normal JSON object
I figured out another way to do it, which is giving me the required results too.
Here I am filtering the values of the query, and then converting it to a list and passing it as a JsonResponse
views.py
def civil_home(request):
if request.method == "POST" and request.is_ajax():
get_cat = request.POST.get('cat[]')
get_court = request.POST.get('court[]')
get_lawT = request.POST.get('lawT[]')
query = Citation.objects.values().filter(law_type__contains ='civil' ,sub_law_type__contains= get_cat, court_name__contains = get_court, law_category__contains = get_lawT)
result = list(query)
return JsonResponse({"status": "success", "result": result})
else:
subuser = request.user
subscription = UserSubscription.objects.filter(user = subuser, is_active = True)
context = {
'usersub': subscription,
}
return render(request, 'civil/civil_home.html', context)
And then I am recieving the reponse here and iterrating over it to print the attributes in the html
js
for (i = 0; i < lawTypeInput.length; i++) {
lawTypeInput[i].addEventListener("click", (e) => {
e.preventDefault();
cat = civilCatval;
court = civilCourtval;
lawT = civillawTypeval;
console.log("this is from ajax : ", cat, court, lawT);
$.ajax({
type: "POST",
headers: { "X-CSRFToken": csrftoken },
mode: "same-origin", // Do not send CSRF token to another domain.
url: "civil",
data: {
"cat[]": civilCatval,
"court[]": civilCourtval,
"lawT[]": civillawTypeval,
},
success: function (response) {
console.log(response.result);
civilData = response.result;
if ((response.status = "success")) {
$("#queryResult").empty();
for (i = 0; i < civilData.length; i++) {
$("#queryResult").append(
`
${civilData[i].title}
<p>${civilData[i].headnote}</p>
`
);
}
} else {
$("#queryResult").empty();
$("#queryResult").append(
`
<p>No Citations Found</p>
`
);
}
},
error: function (error) {
console.log(error);
},
});
});
}
A csrf_token can be mentioned at the top of the html page and then it can be passed in the header to avoid any conflict.
How to apply { parse_mode: 'Markdown' } for reply with InlineKeyboardButton ?
const Telegraf = require("telegraf");
const Extra = require("telegraf/extra");
const Markup = require("telegraf/markup");
const keyboard = Markup.inlineKeyboard([
Markup.urlButton("❤️", "http://telegraf.js.org"),
Markup.callbackButton("Delete", "delete")
]);
const myReply = "Hello *mate*, __where are you ?__"
bot.on("message", ctx =>
ctx.telegram.sendMessage(ctx.chat.id, myReply, Extra.markup(keyboard))
);
Is there any option to add markdown style for message with InlineKeyboardButton ?
Telegraf 4
According to Telegraf 4.0 changelog, Extra is removed entirely.
If you have an inline-keyboard in a simple ctx.reply() (see the example), just use .replyWithHTML() or .replyWithMarkdown() or .replyWithMarkdownV2() instead of .reply().
ctx.replyWithMarkdownV2(
'*formatted* text',
Markup.inlineKeyboard([
Markup.button.callback('Coke', 'Coke'),
Markup.button.callback('Dr Pepper', 'Dr Pepper'),
Markup.button.callback('Pepsi', 'Pepsi')
])
)
If you have a more complex situation, you can pass an object like below as the appropriate argument to the ctx.reply() or ctx.telegram.sendMessage() or bot.telegram.editMessageText() etc.:
const extraObject = {
parse_mode: 'HTML',
...Markup.inlineKeyboard([
Markup.button.callback('Coke', 'Coke'),
Markup.button.callback('Pepsi', 'Pepsi'),
]),
}
ctx.telegram.sendMessage(ctx.chat.id, 'My <b>formatted</b> reply', extraObject)
To add Markdown styling to your message, chain markdown() to Extra.markup(), like this:
const keyboard = Markup.inlineKeyboard([
Markup.urlButton("❤️", "http://telegraf.js.org"),
Markup.callbackButton("Delete", "delete")
]);
const myReply = "Hello *mate*, _where are you ?_"
bot.on("message", ctx => {
ctx.telegram.sendMessage(ctx.chat.id, myReply, Extra.markdown().markup(keyboard));
});
I have a form in which I save some details and upload a file. I have a factory from which I get some data. When I use ng-file-upload the factory is undefined. Here is the code:
angular.module('tollApp')
.controller('mstrEmployeeCtrl',['Upload','$window',
function(Upload,$window,$scope,$http,$timeout,$filter,$mdToast,userDetailsFactory){
$scope.ipForHttp = userDetailsFactory.getUserDetailsFromFactory().ipAddress;
//`userDetailsFactory` is undefined
$scope.SaveData = function(){
// $scope.dobObj = new Date($scope.Emp.EmpDoB);
if ($scope.myform.$valid && $scope.passwordEqual) {
Upload.upload({
url: '$scope.ipForHttp+"addEmployee?EmpID="+$scope.Emp.EmpID,
data:{file:file} //pass file as data, should be user ng-model
})
.then(function(response){
$scope.error=response.data.code;
console.log(JSON.stringify(response));
console.log($scope.error+" SCOPE");
})
$scope.submitted = false;
}
};
}
]);
The error:
angular.min.js:117 TypeError: Cannot read property 'getUserDetailsFromFactory' of undefined
at new <anonymous> (http://192.168.1.19/public/javascripts/mstrEmployeeCtrl.js:4:38)
at Object.instantiate (http://192.168.1.19/public/javascripts/angular.min.js:41:477)
at http://192.168.1.19/public/javascripts/angular.min.js:90:3
at Object.link (http://192.168.1.19/node_modules/angular-route/angular-route.min.js:7:274)
at http://192.168.1.19/public/javascripts/angular.min.js:16:230
at ia (http://192.168.1.19/public/javascripts/angular.min.js:81:35)
at n (http://192.168.1.19/public/javascripts/angular.min.js:66:176)
at g (http://192.168.1.19/public/javascripts/angular.min.js:58:429)
at http://192.168.1.19/public/javascripts/angular.min.js:58:67
at http://192.168.1.19/public/javascripts/angular.min.js:62:430 <div data-ng-view="" class="ng-scope" data-ng-animate="1">
The factory which is undefined:
angular.module('tollApp')
.controller('indexController', function($scope,$http,$window,userDetailsFactory){
$scope.usernameFromServer={};
$scope.getUserDetails = function(){
$http({
method:'GET',
url:'http://192.168.1.19:80/getUserDetails'
})
.then(function(response){
// console.log(JSON.stringify(response));
userDetailsFactory.setUserDetailsInFactory(response.data);
$scope.usernameFromFactory = userDetailsFactory.getUserDetailsFromFactory().usernameFromSession;
// $scope.usernameFromServer = userDetailsFactory.getUserDetailsFromFactory().username;
// console.log(JSON.stringify($scope.usernameFromFactory)+"usernameFromFactory");
})
}
$scope.logout = function(request,response){
$http({
method:'GET',
url:'/logout'
})
.then(function(response){
console.log(JSON.stringify(response));
if(response.data=="logout"){
$window.location.href="http://192.168.1.19:80/login";
}
})
}
console.log("indexController");
}).factory('userDetailsFactory',function(){
var user = {};
return {
setUserDetailsInFactory : function(val){
user.useridFromSession = val[0].UserID;
user.usernameFromSession = val[0].UserName;
user.userroleFromSession = val[0].UserRole;
user.clientidFromSession = val[0].ClientID;
user.ipAddress = "http://192.168.1.19:80/";
// user.ipAddress = "http://easypaytoll.com/";
// console.log("in set "+user.clientidFromSession);
},
getUserDetailsFromFactory : function(){
return user;
}
};
});
It's an injection problem.
You have to put the userDetailsFactory in the array :
angular.module('tollApp')
.controller('mstrEmployeeCtrl',['Upload','$window','$scope', '$http','$timeout','$filter','$mdToast','userDetailsFactory'
function(Upload,$window,$scope,$http,$timeout,$filter,$mdToast,userDetailsFactory){
Edit 1
Your error is clear : userDetailsFactory is not defined. How did you define this factory ? Is it in the same module ? If not, did you add its module to the app's module dependencies ?
I'm building a complete crud using laravel + angularjs, but I have problems in the "edit" part.
It's an internal server error, so I don't know what it means and I need help.
Error "GET localhost/crudtcc/public/api/v1/colaboradores/editar/3 500 (Internal Server Error)"
the javascript file:
app.controller('colaboradoresController', function($scope, $http, API_URL) {
$http.get(API_URL + "colaboradores")
.success(function(response) {
$scope.colaboradores = response;
});
$scope.toggle = function(modalstate, id_colaborador) {
$scope.modalstate = modalstate;
switch (modalstate) {
case 'add':
$scope.form_title = "Novo colaborador";
$scope.colaborador = null;
break;
case 'edit':
$scope.form_title = "Dados do colaborador";
$scope.id_colaborador = id_colaborador;
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
break;
default:
break;
}
$('#myModal').modal('show');
}
$scope.save = function(modalstate, id_colaborador) {
var url = API_URL + "colaboradores/salvar";
if (modalstate === 'edit') {
url += "/editar/" + id_colaborador;
}
$http({
method: 'POST',
url: url,
data: $.param($scope.colaborador),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(response) {
console.log(response);
location.reload();
}).error(function(response) {
console.log(response);
alert('Um erro ocorreu. Check a log para mais detalhes.');
});
}
$scope.confirmDelete = function(id_colaborador) {
var isConfirmDelete = confirm('Tem certeza que deseja excluir o registro?');
if (isConfirmDelete) {
$http({
method: 'DELETE',
url: API_URL + 'colaboradores/remover/' + id_colaborador
}).
success(function(data) {
console.log(data);
location.reload();
}).
error(function(data) {
console.log(data);
alert('Falha na exclusão');
});
} else {
return false;
}
}
});
the routes file:
<?php
namespace App\Http\Controllers;
$colaborador = new Colaborador;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Usuario;
use App\Http\Controllers\Controler;
use App\Colaborador;
class Colaboradores extends Controller
{
public function index()
{
return Colaborador::orderBy('id_colaborador', 'asc')->get();
}
public function salvar(Request $request)
{
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return 'Colaborador salvo com sucesso! ID: ' . $colaborador->id_colaborador;
}
public function update(Request $request,$id_colaborador)
{
$colaborador = Colaborador::find($id_colaborador);
$colaborador->nome = $request->input('nome');
$colaborador->rg = $request->input('rg');
$colaborador->orgao_expedidor = $request->input('orgao_expedidor');
$colaborador->cpf = $request->input('cpf');
$colaborador->estado_civil = $request->input('estado_civil');
$colaborador->sexo = $request->input('sexo');
$colaborador->nome_pai = $request->input('nome_pai');
$colaborador->nome_mae = $request->input('nome_mae');
$colaborador->naturalidade = $request->input('naturalidade');
$colaborador->data_nascimento = $request->input('data_nascimento');
$colaborador->login = $request->input('login');
$colaborador->senha = $request->input('senha');
$colaborador->siape = $request->input('siape');
$colaborador->pis = $request->input('pis');
$colaborador->rua = $request->input('rua');
$colaborador->numero = $request->input('numero');
$colaborador->bairro = $request->input('bairro');
$colaborador->cidade = $request->input('cidade');
$colaborador->estado = $request->input('estado');
$colaborador->cep = $request->input('cep');
$colaborador->telefone_fixo = $request->input('telefone_fixo');
$colaborador->telefone_celular= $request->input('telefone_celular');
$colaborador->telefone_comercial = $request->input('telefone_comercial');
$colaborador->email = $request->input('email');
$colaborador->save();
return "Sucesso atualizando Colaborador #" . $colaborador->id_colaborador;
}
public function remove(Request $request, $id_colaborador)
{
$colaborador = Colaborador::where("id_colaborador", $id_colaborador);
$colaborador->delete();
return "Colaborador #". $request->input('id_colaborador'). " excluido com sucesso!";
}
public function editar($id_colaborador)
{
return Colaborador::where("id_colaborador", $id_colaborador);
}
}
?>
and the routes file...
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get("/colaboradores/gercolaboradores",
function() {
return view("/colaboradores/gerenciarcolaboradores");
});
Route::get("/api/v1/colaboradores/","Colaboradores#index");
Route::get("/api/v1/colaboradores/editar/{id_colaborador}","Colaboradores#editar");
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
Route::post('/api/v1/colaboradores/salvar', 'Colaboradores#salvar');
Route::delete('/api/v1/colaboradores/remover/{id_colaborador}', 'Colaboradores#remove');
?>
You should write your request on Angular side as:
$http.post(API_URL + 'colaboradores/editar/' + id_colaborador, {YOUR_DATA})
.success(function(response) {
console.log(response);
$scope.colaborador = response;
});
and pass the parameters you want to send to backend.
Please refer to: https://docs.angularjs.org/api/ng/service/$http.
Explanation:
you're using angular GET
$http.get(API_URL + 'colaboradores/editar/' + id_colaborador)
and you defined your route in Laravel as POST
Route::post('/api/v1/colaboradores/salvar/editar/{id_colaborador}',
'Colaboradores#update');
GET is not passing any data except trough url, and you're trying to get that data as if you've sent it trough POST request.
You can find a short explanation on GET and POST requests on the following links: http://www.w3schools.com/tags/ref_httpmethods.asp and What is the difference between POST and GET?
I am getting error while creating customer
AuthenticationError at /vissa/assign-plan/
My js
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
{% if cust %}
$(document).ready(function() {
braintree.setup("{{ client_token }}", "dropin", {
container: "checkout",
form: "checkoutForm"
});
$("#submitPayment").on("click", function () {
$("button").off("click");
$("a").off("click");
$('body').off("click");
var btn = $(this).button("loading")
setTimeout(function () {
btn.button('reset');
}, 3500)
});
});
</script>
{% endif %}
And client token i am trying to get in context processor.
def payment_data(request):
try:
userone = UserProfile.objects.get(user=request.user)
indi_user = IndividualUser.objects.get(user_profile=userone)
plan = int(indi_user.selected_plan)
amount = int(plan)
except:
plan = None
amount = None
try:
merchant_obj = UserMerchantId.objects.get(user=request.user)
cust = True
merchant_customer_id = merchant_obj.customer_id
print merchant_customer_id
client_token = braintree.ClientToken.generate({
"customer_id": merchant_customer_id
})
except:
cust = False
client_token = None
try:
custom = Transaction.objects.filter(user=request.user)[0]
paid = custom.success
except:
paid = False
return {'cust':cust, "plan":plan,"amount": amount, "paid": paid,"client_token":client_token} #"plan": plan}
but i am getting above error.
if i tried
client_token = braintree.ClientToken.generate()
getting authentication error.
I am not getting how to create client token in django.
is there a way to create client token without customer_id?
Creating customer.
def new_user_receiver( instance, *args, **kwargs):
try:
merchant_obj = UserMerchantId.objects.get(user=instance)
except:
new_customer_result = braintree.Customer.create({
"first_name": instance.first_name,
"last_name": instance.last_name,
"email": instance.email,
"phone": instance.get_profile().telephone_number
})
if new_customer_result.is_success:
merchant_obj, created = UserMerchantId.objects.get_or_create(user=instance)
merchant_obj.customer_id = new_customer_result.customer.id
merchant_obj.save()
print """Customer created with id = {0}""".format(new_customer_result.customer.id)
else:
print "Error: {0}".format(new_customer_result.message)
It worked after making the change
import braintree
braintree.Configuration.configure(braintree.Environment.Production,
merchant_id=settings.BRAINTREE_MERCHANT_ID,
public_key=settings.BRAINTREE_PUBLIC_KEY,
private_key=settings.BRAINTREE_PRIVATE_KEY)
in production instead of "Sandbox" need to use "Production".