Am newbie to coldfusion please give me solution how to insert username unique in coldfusion?
Is there any default option in coldfusion like(Maxlength,required etc...) or else we checked query with that form data username once count greater than zero means return false to submit data Is it correct?
You could use ajax to invoke a function with the username as a parameter and check using the select query to see if the username exists.
<cffunction name="checkUsernameExists" access="public" returnType="numeric" >
<cfargument required="yes" name="username" type="string" >
<cfset local.userExistsFlag = 0 >
<cfquery name="qCheckUsernameExists" datasource="datasource_name" >
select username
from table_name
where username = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.username#" >
</cfquery>
<cfif qCheckUsernameExists.recordcount >
<cfset local.userExistsFlag = 1 >
</cfif>
<cfreturn local.userExistsFlag >
</cffunction>
If the returned value is 1 then the username exists else username doesn't exist.
$.ajax({
type: "POST",
url: "user.cfc?method=checkUsernameExists",
data: {"username":username},
success: function(data) {
//handle the response here
}
});
Related
I have function that should save some form fields. This function is able to process multiple insert rows. So far I was able to create logic to handle this but the only issue so far I have once user tries to save the record. The server response looks like this:
The system has attempted to use an undefined value, which usually indicates a programming error, either in your code or some system code. Null Pointers are another name for undefined values. coldfusion
At first I was looking and trying to find which value is not defined/missing in my function but so far I couldn't detect the issue. The next thing I did was commenting out the cfquery. After that I was getting message Form successfully saved.. This tells me that my code is breaking inside of the cfquery tag. Here is example of my code:
<cffunction name="saveRecords" access="remote" output="false" returnformat="JSON">
<cfargument name="formID" type="string" required="true" default="">
<cfargument name="status1" type="string" required="true" default="0">
<cfargument name="status2" type="string" required="true" default="0">
<cfargument name="status3" type="string" required="true" default="0">
<cfargument name="status4" type="string" required="true" default="0">
<cfargument name="status5" type="string" required="true" default="0">
<cfargument name="comment1" type="string" required="true" default="">
<cfargument name="comment2" type="string" required="true" default="">
<cfargument name="comment3" type="string" required="true" default="">
<cfargument name="comment4" type="string" required="true" default="">
<cfargument name="comment5" type="string" required="true" default="">
<cfset local.fnResults = structNew() />
<cfset local.runProcess = true />
<cfset local.arrStatus = arrayNew(1) />
<cfloop collection="#arguments#" item="i">
<cfif findNoCase(left(i,6), "status") and arguments[i] eq 1>
<cfset arrayAppend(local.arrStatus, right(i,1)) />
</cfif>
</cfloop>
<cfset local.frmValidation = {
formID : len(arguments.formID),
status1 : ArrayContains([0,1], trim(arguments.status1)),
status2 : ArrayContains([0,1], trim(arguments.status2)),
status3 : ArrayContains([0,1], trim(arguments.status3)),
status4 : ArrayContains([0,1], trim(arguments.status4)),
status5 : ArrayContains([0,1], trim(arguments.status5))
}/>
<cfloop collection="#frmValidation#" item="i">
<cfif !frmValidation[i] or !arrayLen(arrStatus)>
<cfset local.runProcess = false />
<cfset local.fnResults = {status: 400, message: "Form data is either missing or incorrect."}>
<cfbreak>
</cfif>
</cfloop>
<cfif runProcess>
<!---
<cfquery name="saveRec" datasource="testDB">
<cfloop array="#arrStatus#" index="i">
INSERT INTO formDetails (
formid,
refid,
status,
comment,
userid,
lastupdate
)
SELECT
<cfqueryparam cfsqltype="cf_sql_numeric" value="#trim(arguments.formID)#">,
#i#,
<cfqueryparam cfsqltype="cf_sql_bit" value="#trim(arguments["status"&i])#">,
<cfqueryparam cfsqltype="cf_sql_varchar" maxlength="8000" value="#trim(arguments["comment"&i])#" null="#!len(trim(arguments["comment"&i]))#">,
<cfqueryparam cfsqltype="cf_sql_varchar" maxlength="6" value="#trim(session.userid)#" null="#!len(trim(session.userid))#">,
#now()#
WHERE NOT EXISTS (
SELECT refid
FROM formDetails
WHERE formid = <cfqueryparam cfsqltype="cf_sql_numeric" value="#trim(arguments.formID)#">
AND refid = #i#
)
</cfloop>
</cfquery>
--->
<cfset local.fnResults = {status: 200, message: "Form successfully saved!"}>
</cfif>
<cfreturn fnResults>
</cffunction>
One thing that I forgot to mention is that before I commented out cfquery, I tried to save the records and error will occur that I mentioned above but at the same time record is saved in database. That is weird since I didn't expect query to execute successfully because of the error. I use Sybase database and here are the details about formDetails table:
column name data type length
recid numeric 18 PK
formid numeric 10 FK
refid numeric 18 FK
status bit 1
comment varchar 8000
userid varchar 6
lastupdate datetime 23
I'm not sure where my code is breaking and why I'm getting an error message about undefined value. If anyone can help or provide some useful resource on how to fix this issue please let me know.
UPDATE
I have been looking for solution on how to fix this problem and I tried using cfscript with UNION ALL. This was suggested from few people and here is example of my code:
remote function saveRecords(required string formID, string status1="0", string status2="0", string status3="0", string status4="0", string status5="0", string comment1="", string comment2="", string comment3="", string comment4="", string comment5="") output=false returnFormat="JSON" {
local.fnResults = structNew();
local.runProcess = true;
local.arrReference = arrayNew(1);
try {
local.frmValidation = {
formID : len(arguments.formID),
status1 : ArrayContains([0,1], arguments.status1),
status2 : ArrayContains([0,1], arguments.status2),
status3 : ArrayContains([0,1], arguments.status3),
status4 : ArrayContains([0,1], arguments.status4),
status5 : ArrayContains([0,1], arguments.status5)
};
for ( i in frmValidation ) {
if ( !frmValidation[i] ) {
local.runProcess = false;
local.fnResults = {status: 400, message: "Form data is either missing or incorrect."};
break;
}
}
for ( fld in arguments ) {
if ( findNoCase(left(fld,6), "status") && arguments[fld] == 1 ) {
arrayAppend(arrReference, right(fld,1));
}
}
if ( runProcess ) {
local.qrySql = "INSERT INTO formDetails(recid, formid, refid, status, comment, userid, lastupdate)";
local.qryParams = [];
for ( idx=1 ; idx<=arraylen(arrReference) ; idx++ ) {
local.referenceID = arrReference[idx];
local.recPK = trim(arguments.formID) & trim(referenceID);
local.statusVal = trim(arguments["status" & local.referenceID]);
local.commentVal = trim(arguments["comment" & local.referenceID]);
if ( idx != 1 ) {
local.qrySql &= " UNION ALL ";
}
local.qrySql &= " SELECT ?,?,?,?,?,?,?";
qryParams.append({cfsqltype="cf_sql_numeric", value=local.recPK});
qryParams.append({cfsqltype="cf_sql_numeric", value=trim(arguments.formID)});
qryParams.append({cfsqltype="cf_sql_numeric", value=local.referenceID});
qryParams.append({cfsqltype="cf_sql_tinyint", value=local.statusVal});
qryParams.append({cfsqltype="cf_sql_varchar", value=local.commentVal, maxlength=8000, null=!len(local.commentVal)});
qryParams.append({cfsqltype="cf_sql_varchar", value=trim(session.userid), maxlength=6, null=!len(trim(session.userid))});
qryParams.append({cfsqltype="cf_sql_timestamp", value=now()});
}
local.qryResult = queryExecute(qrySQL, qryParams, {datasource="#application.datasource#", result="insertRecords"});
local.fnResults = {result: insertRecords, sql: qrySql, params: qryParams, array: arrReference, args: arguments, status: 200, message: "Form successfully saved!"};
}
} catch (any e) {
local.fnResults = {sql: qrySql, params: qryParams, error: e, status: 400, message: "Error! Something went wrong..."};
}
return fnResults;
}
After I tried to save the record from I got the message Something went wrong.... I looked in response and all I can see is error that is pointing to the this line:
local.qryResult = queryExecute(qrySQL, qryParams, {datasource="#application.datasource#", result="insertRecords"});
I checked the database and records are in there. No details about this error nothing. At least I'm not getting an error that I described in the question above but still no clue what is causing my code to crash.
I've found two things
1) you insert query does not have any value. INSERT INTO tablename( columns ... ) VALUES ( column values.. ) But you have missed VALUE key word in your query.
2) Whenever you are going to do two query operations in single cfquery tag you should add some Connection String in your testDB data sources. Which is available in CFML admin part. Open you data source and set below options. In CFML admin :
If you are using Lucee means: Please check the below options in your data source which is available in lucee server / web admin,
I am working with ColdFusion and am new to the language. I want to perform a database operation with the given value and return the result via ajax response, when the onBlur event of a textbox is triggered. Please check my code below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#username").blur(function() {
alert("This input field has lost its focus.");
var userNameVal = $(this).val();
if(userNameVal != "") {
$.get("myajax.cfc?method=getuser&userName=userNameVal", function(res) {
$("#userid").val=res;
}, "JSON");
}
});
});
</script>
<input type='textbox' name='username' id='username' />
<input type='hidden' name='userid' id='userid'/>
myajax.cfc:
<cfcomponent>
<cffunction name="getuser" access="remote" returntype="Integer">
<cfargument name="userName" type="string" required="yes">
<cftry>
<cfquery name="getUser" datasource="ajax_example">
select USER_ID
from user u
where u.firstname=userName;
<cfqueryparam value = "#url.userName#" cfsqltype="cf_sql_varchar">
</cfquery>
<cfcatch>
<cfoutput>
#cfcatch.Detail#<br />
#cfcatch.Message#<br />
#cfcatch.tagcontext[1].line#:#cfcatch.tagcontext[1].template#
</cfoutput>
</cfcatch>
</cftry>
<cfreturn getUser.USER_ID/>
</cffunction>
</cfcomponent>
From my ajax.cfc response I want to return USER_ID to my ajax call. How can I do this?
You need to pass the actual value of the variable named userNameVal in the query string. Like this:
$.get("myajax.cfc?method=getuser&userName="+userNameVal, function(res) {
$("#userid").val=res;
}, "JSON");
And as #Dan suggested, the way you are using cfqueryparam, is wrong. It should be done like this:
<cfquery name="getUser" datasource="ajax_example">
select USER_ID
from user u
where u.firstname=<cfqueryparam value = "#arguments.userName#" cfsqltype="cf_sql_varchar">
</cfquery>
You have this code:
where u.firstname=userName;
<cfqueryparam value = "#url.userName#" cfsqltype="cf_sql_varchar">
This is not valid sql. The semi-colon terminates the command and ColdFusion will throw an error because the cfqueryparam tag comes afterwards.
You also have this query in a cftry block. The cfcatch code outputs data. If you were calling this function from ColdFusion code, you would see the cfcatch information in your web browser. However, you are calling it with ajax. It's outputting to a black hole. Also, you are getting no ColdFusion error because of the try/catch. Plus the cfcatch block does not include a cfreturn tag so nothing gets returned to javascript.
Another error is that you are using the wrong scope in your query. This:
value = "#url.userName#"
should be this:
value = "#arguments.userName#"
You are attempting to do too many things at once. I suggest calling your method with ColdFusion until you get it working properly. Then call it with ajax.
I am using CFLDAP to have users get authenticated using active directory. I am trying to write an if statement in case the users information does not come back as authenticated. I thought I could check by using <cfif AuthenticateUser.RecordCount gt 0> which is working as long as the information is correct but if the wrong information is entered and nothing is authenticated it is not running the else statement. Any help with this would be greatly appreciated!
<cfldap action="query"
name="AuthenticateUser"
attributes="dn,mail,givenname,sn,samaccountname,memberof"
start="DC=domain,DC=net"
filter="(&(objectclass=user)(samAccountName=#trim(form.user_name)#))"
server="servername"
Port="389"
username="tc\#trim(form.user_name)#"
password="#trim(form.user_pass)#">
<cfoutput>#AuthenticateUser.RecordCount#</cfoutput>
<!--- Get all records from the database that match this users credentials --->
<cfquery name="userVerify" datasource="test">
SELECT *
FROM dbo.Users
WHERE user_name = <cfqueryparam value="#AuthenticateUser.samaccountname#" cfsqltype="cf_sql_varchar" />
</cfquery>
<cfif AuthenticateUser.RecordCount gt 0>
<!--- This user has logged in correctly, change the value of the session.allowin value --->
<cfset session.allowin = "True" />
<cfset session.employee_number = userVerify.employee_number />
<!--- Now welcome user and redirect to "index.html" --->
<script>
self.location="../dashboard/dashboard.cfm";
</script>
<cfelse>
<!--- this user did not log in correctly, alert and redirect to the login page --->
<script>
alert("Your credentials could not be verified, please try again!");
self.location="Javascript:history.go(-1)";
</script>
</cfif>
I have also tried: <cfif len(AuthenticateUser)>
This is how I do it. I try to run a query against our domain using the supplied username and password. If the supplied username and password are not valid, an error is generated.
<cftry>
<cfldap action="Query"
name="ADResult"
attributes="dn"
start="DC=domain,DC=net"
filter="sAMAccountName=administrator"
server="servername"
scope = "subtree"
username="#arguments.username#"
password="#arguments.password#" />
<cfset isAuthenticated = true />
<cfcatch type="any">
<cfset isAuthenticated = false />
</cfcatch>
</cftry>
<cfreturn isAuthenticated />
I wrap this up in a function called "authenticate" and expose it via a web service that I call from my apps. If I then need additional details about the user (mail, givenName, etc), I have another function in the same web service that I will call after I am sure the user has been authenticated. Note that in this other function I'm using my administrator username and password to run the query.
<cfldap action="Query"
name="ADResult"
attributes="mail,givenName"
start="DC=domain,DC=net"
filter="sAMAccountName=#arguments.username#"
server="servername"
scope = "subtree"
username="administrator"
password="myAdminPassword" />
I take the results of this, populate a query object or a structure, and return that to the calling function.
So the entire process sort of looks like this:
<cfset objAD = createobject("webservice", "http://mywebservice.com") />
<cfset isAuthenticated = objAD.authenticate(form.username, form.password) />
<cfif isAuthenticated>
<cfset userDetails = objAD.getUserDetails(form.username)>
</cfif>
Hope this helps.
This is a formatted comment. You are trying to do too much at once. Go one step at a time. Start with this:
<cfdump var="before cfldap tag<br />">
<cfldap action="query"
name="AuthenticateUser"
etc
>
<cfdump var="after cfldap tag<br />">
<cfdump var = "#AuthenticateUser#">
<cfdump var="after cfdump<br />">
Run this code with both valid and not valid credentials. Look at what you get. React accordingly.
I think it throws an error when the query fails. Try this:
<cftry>
<cfldap action="query"
name="AuthenticateUser"
attributes="dn,mail,givenname,sn,samaccountname,memberof"
start="DC=domain,DC=net"
filter="(&(objectclass=user)(samAccountName=#trim(form.user_name)#))"
server="servername"
Port="389"
username="tc\#trim(form.user_name)#"
password="#trim(form.user_pass)#">
<cfset LoginStatus = "Success">
<cfcatch type="any">
<cfset LoginStatus = "Failed">
</cfcatch>
</cftry>
Then your cfif would be something like this:
<cfif LoginStatus eq "Success">
<!--- This user has logged in correctly, change the value of the session.allowin value --->
<cfset session.allowin = "True" />
<cfset session.employee_number = userVerify.employee_number />
<!--- Now welcome user and redirect to "index.html" --->
<script>
self.location="../dashboard/dashboard.cfm";
</script>
<cfelse>
<!--- this user did not log in correctly, alert and redirect to the login page --->
<script>
alert("Your credentials could not be verified, please try again!");
self.location="Javascript:history.go(-1)";
</script>
</cfif>
I think this works on CF9.
I'm attempting to use the Coldfusion Login Wizard to query Active Directory, however I'm having a problem with the directory structure. Essentially, I need to query from multiple nested OUs that are under the same root OU. So for instance, the OU "Admin" and "Staff" are children of the OU "School Users". I'm able to use the following code to successfully query each sub OU individully, but I can't query the root (School Users) OU.
<!-- This is the include file that sets the attributes and collects the username and password passed by the user-->
<cfset args.authtype = "LDAP">
<cfset args.server = "ads.schoolname.org">
<cfset args.port = "389">
<cfset args.start = "dc=schoolname, dc=org">
<cfset args.suser = "usr">
<cfset args.spwd = "password">
<cfset args.queryString = "cn={username},OU=ADMIN,OU=SCHOOL USERS,DC=SCHOOLNAME,DC=ORG">
<!-- The following is a snippet of the authenticate file that takes the above info and attempts to query and authenticate the user -->
<cffunction name="ldapauth" access="private" output="true" returntype="struct" hint="Authenticate against a LDAP server." >
<cfargument name="lServer" required="true" hint="The LDAP server.">
<cfargument name="lPort" hint="The port the LDAP server is running on.">
<cfargument name="sUsername" required="true" hint="The username that was set in the Login Wizard.">
<cfargument name="sPassword" required="true" hint="The password that was set in the Login Wizard.">
<cfargument name="uUsername" required="true" hint="The username that was passed in from the client.">
<cfargument name="uPassword" required="true" hint="The password that was passwd in from the client.">
<cfargument name="sQueryString" required="true" hint="The string to be passed to the LDAP server">
<cfargument name="lStart" required="true">
<cfset var retargs = StructNew()>
<cfset var username = replace(sQueryString,"{username}",uUserName)>
<cfldap action="QUERY"
name="userSearch"
attributes="dn"
start="#arguments.lStart#"
server="#arguments.lServer#"
port="#arguments.lPort#"
username="#arguments.sUsername#"
password="#arguments.sPassword#" >
<!--- If user search failed or returns 0 rows abort --->
<cfif userSearch.recordCount EQ "" >
<cfoutput>Error</cfoutput>
</cfif>
<!--- pass the user's DN and password to see if the user authenticates
and get the user's roles --->
<cfldap
action="QUERY"
name="auth"
attributes="dn,roles"
start="#arguments.lStart#"
server="#arguments.lServer#"
port="#arguments.lPort#"
username="#username#"
password="#arguments.uPassword#" >
<!--- If the LDAP query returned a record, the user is valid. --->
<cfif auth.recordCount>
<cfset retargs.authenticated="YES">
<!--- return role here, default role is always "user" --->
<cfset retargs.roles = "user">
</cfif>
<cfreturn retargs>
</cffunction>
Thanks for the help
You can use scope attribute of cfldap and set it to subtree:
It will allow search from the start entry and all levels below it.
I figured out the issue. I needed to add the scope of subtree, but also change the way the username was being authenicated from CN=something to an email address with the domain
I'm getting a 500 Internal Server Error trying to use http://fineuploader.com/ with Coldfusion server side https://github.com/Widen/fine-uploader-server/tree/master/coldfusion
Console says:
[FineUploader] Error when attempting to parse xhr response text (SyntaxError: Unexpected token <) at this line in window.console.log('<' + level + '> ' + message);
It seems its coming from the response message in the Server CFC.
<!--- Code provided by Pegasus Web Productions LLC - www.pegweb.com --->
<!--- get stuck use the forums http://github.com/Widen/fine-uploader --->
<!--- Tested with Adobe CF Enterprise 9.x and Fine Uploader --->
<CFCOMPONENT HINT="I do your uploads from Fine Uploader" >
<!--- function for single file submission uploads where XHR is not supported ex:->
<CFFUNCTION NAME="Upload" ACCESS="remote" OUTPUT="false" RETURNTYPE="any" RETURNFORMAT="JSON" >
<CFARGUMENT NAME="qqfile" TYPE="string" REQUIRED="true" />
<CFSET var local = structNew() >
<CFSET local.response = structNew() >
<CFSET local.requestData = GetHttpRequestData() ><!--- get the request headers and body --->
<CFSET UploadDir = "/Test/file2" ><!--- set your upload directory here ex: c:\website\www\images\ --->
<!--- check if XHR data exists --->
<CFIF len(local.requestData.content) GT 0 >
<CFSET local.response = UploadFileXhr(arguments.qqfile, local.requestData.content) >
<CFELSE><!--- no XHR data so process this as standard form submission --->
<!--- upload the file --->
<CFFILE ACTION="upload" FILEFIELD="form.qqfile" DESTINATION="#UploadDir#" NAMECONFLICT="makeunique" >
<!--- populate our structure with information about the image we just uploaded in case we want to use this later for CFIMAGE tags or any other processing --->
<CFSET local.metaData = { clientFile=FILE.clientFile, clientFileExt=FILE.clientFileExt, clientFileName=FILE.clientFileName, contentSubType=FILE.contentSubType, contentType=FILE.contentType, fileSize=FILE.fileSize } />
<!--- return the response --->
<CFSET local.response['success'] = true >
<CFSET local.response['type'] = 'form' >
</CFIF>
<CFRETURN local.response >
</CFFUNCTION>
<!--- function for browsers that support XHR ex: Almost anything but IE --->
<CFFUNCTION NAME="UploadFileXhr" ACCESS="private" OUTPUT="false" RETURNTYPE="struct" >
<CFARGUMENT NAME="qqfile" TYPE="string" REQUIRED="true" />
<CFARGUMENT NAME="content" TYPE="any" REQUIRED="true" />
<CFSET var local = structNew() >
<CFSET local.response = structNew() >
<CFSET UploadDir = "" ><!--- set your upload directory here ex: c:\website\www\images\ --->
<!--- write the contents of the http request to a file. The filename is passed with the qqfile variable --->
<CFFILE ACTION="write" FILE="#UploadDir#\#arguments.qqfile#" OUTPUT="#arguments.content#" NAMECONFLICT="makeunique" >
<!--- populate our structure with information about the image we just uploaded in case we want to use this later for CFIMAGE tags or any other processing --->
<CFSET local.metaData = { clientFile=FILE.clientFile, clientFileExt=FILE.clientFileExt, clientFileName=FILE.clientFileName, contentSubType=FILE.contentSubType, contentType=FILE.contentType, fileSize=FILE.fileSize } />
<!--- return custom JSON if desired--->
<CFSET local.response['success'] = true >
<CFSET local.response['type'] = 'xhr' >
<CFRETURN local.response >
</CFFUNCTION>
Calling page
<div id="thumbnail-fine-uploader">
</div>
<script src="/js/jQueryv1.9.1.js">
</script>
<script src="/Test/file2/jquery.fineuploader-3.4.1.js">
</script>
<script>
$(document).ready(function(){
var thumbnailuploader = new qq.FineUploader({
element: $('#thumbnail-fine-uploader')[0],
request: {
endpoint: 'image-uploader.cfc?method=Upload'
},
multiple: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
sizeLimit: 51200 // 50 kB = 50 * 1024 bytes
},
callbacks: {
onComplete: function(id, fileName, responseJSON){
if (responseJSON.success) {
$('#thumbnail-fine-uploader').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
}
}
});
});
</script>
Got it working, I was missing my upload directory path in the second method.
<CFSET UploadDir = "#expandpath('/test/file2')#" >
Thanks for the help