Conversion of my alfresco javascript file into java class [duplicate] - javascript

This question already has an answer here:
Auto-generation of email with username and random password on creation of new user
(1 answer)
Closed 6 years ago.
I need to convert this javascript file into java code.Please help
if (document.isContainer && document.displayPath == "/Company Home/User Homes") {
var owner = document.properties["cm:owner"];
var pNode = people.getPerson(owner);
if (pNode!=null && pNode.exists()){
var userName = pNode.properties.userName;
var email = pNode.properties.email;
var randPassword = Math.random().toString(36).substr(2, 30)+"-"+(Date.now());
people.setPassword(userName, randPassword);
logger.debug("Invitation mail: User "+userName+" password has been changed.");
var mail = actions.create("mail");
//mail.parameters.from = "noreply#customdomain";
mail.parameters.to = email;
mail.parameters.subject = "Welcome to the Site, login: "+userName+", password: "+randPassword;
mail.parameters.template = companyhome.childByNamePath("Data Dictionary/Email Templates/Invite Email Templates/invite_user_email.ftl");
var templateModel = new Array();
templateModel['newPassword'] = randPassword; // use ${newPassword} expression inside template
mail.parameters.template_model = templateModel;
mail.executeAsynchronously(document);
logger.debug("Invitation mail has been sent to "+email);
} else {
logger.warn("Invitation mail: User not found: "+owner);
}
} else {
logger.warn("Invitation mail: Document "+document.name+" / "+document.nodeRef+" is not a user home folder.");
}

Hope this should help you.
public void createUser()
{
final String randPassword = getRandonPassword();
final String userName= "someuser";
final String email = "someuser#example.com";
authenticationService.setAuthentication(userName, randPassword.toCharArray());
System.out.println(randPassword);
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>()
{
public Void doWork() throws Exception
{
Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
properties.put(ContentModel.PROP_USERNAME,userName);
properties.put(ContentModel.PROP_PASSWORD,randPassword);
properties.put(ContentModel.PROP_EMAIL,email);
NodeRef personNodeRef = personService.createPerson(properties);
personService.notifyPerson(userName, randPassword);
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
private String getRandonPassword()
{
Calendar calendar = Calendar.getInstance();
SecureRandom random = new SecureRandom();
String randomPassword = new BigInteger(130, random).toString(32);
randomPassword = randomPassword +"-" + calendar.getTimeInMillis();
return randomPassword ;
}

Related

I want to the signup form details and login using those details in localstorage with NodeJS

I'm trying for 5 days. I couldn't come up with the solution.I'm a student.
function createUser(){
let user_name = document.getElementById("name").value;
let user_ph = document.getElementById("tel").value;
let user_dob = document.getElementById("date").value;
let new_passwd = document.getElementById("new-password").value;
let user_passwd = document.getElementById("confirm-password").value;
let user_data = new Array();
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph!=user_ph}))
{user_data.push({
"user_name": user_name,
"user_ph": user_ph,
"user_dob": user_dob,
"user_passwd": user_passwd
})
alert("account created for this mobile number");
localStorage.setItem("users",JSON.stringify(user_data));
window.location.href="./login.html";
}
else
{
alert("This number is already linked with another account");
window.location.href = "./reg.html";
}
}
I tried this code and it actually store the data in array even with the empty data and the page don't go to the other page. It stays there.
function login(){
let user_tel = document.getElementById("tel").value;
let user_passwd = document.getElementById("password").value;
user_data = JSON.parse(localStorage.getItem("users"))?JSON.parse(localStorage.getItem("users")):[]
if(user_data.some((v)=>{return v.user_ph==user_ph && v.user_passwd==user_passwd})){
alert("welcome!");
//window.location.href="../profiles/home.html";
}
else
{
alert("Phone number and password is not right")
window.location.href="./login.html"
}
}
this is code for my login page

Getting Script on Top of the page so getting error like $ not define

i am use asp.net core code for popup and append html and js file in main view but i get error like $ not found if anyone know how to solve please help
My ActionFilter Code:-
private readonly IStoreContext _storeContext;
private readonly ISettingService _settingService;
private readonly ILogger _logger;
private readonly ILocalizationService _localizationService;
private readonly IWorkContext _workContext;
private readonly ITopicService _topicService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
#endregion
#region const
public PopupEngageFilterAttribute()
{
this._storeContext = EngineContext.Current.Resolve<IStoreContext>();
this._settingService = EngineContext.Current.Resolve<ISettingService>();
this._logger = EngineContext.Current.Resolve<ILogger>();
this._localizationService = EngineContext.Current.Resolve<ILocalizationService>();
this._workContext = EngineContext.Current.Resolve<IWorkContext>();
this._topicService = EngineContext.Current.Resolve<ITopicService>();
this._newsLetterSubscriptionService = EngineContext.Current.Resolve<INewsLetterSubscriptionService>();
}
#endregion
#region methods
public void PopupEngageOnResultExecuted(ActionExecutedContext filterContext)
{
var storeId = _storeContext.CurrentStore.Id;
LicenseImplementer licenseImplementer = new LicenseImplementer();
// load plugin settings
var _setting = _settingService.LoadSetting<PopupEngageSetting>(storeId);
var allStoreSettings = _settingService.LoadSetting<PopupEngageSetting>(0);
//check plugin is enabled or not
if (_setting.PopupEngageEnabled)
{
// check license
//if (!licenseImplementer.IsLicenseActive(allStoreSettings.LicenseKey, allStoreSettings.OtherLicenseSettings))
// return;
StringBuilder sb = new StringBuilder();
string bioepEngageScript = string.Empty;
string popupEngageView = string.Empty;
string popupEngageScript = string.Empty;
string newsLetterScript = string.Empty;
// get current customer
var customer = _workContext.CurrentCustomer;
// check customer cart
string customerCart = Convert.ToString(customer.HasShoppingCartItems);
// set cookie for customer cart
filterContext.HttpContext.Response.Cookies.Append("CustomerCart", customerCart, new CookieOptions() { Path = "/", HttpOnly = false, Secure = false });
if(customerCart == "True")
{
// get bioep script file
Stream bioepScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.bioep.min.js");
if (bioepScriptFile != null)
using (StreamReader reader = new StreamReader(bioepScriptFile))
{
bioepEngageScript = reader.ReadToEnd();
}
// get PopupEngage script
string path = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Script"), "PopupEngage.js");
if (File.Exists(path))
{
popupEngageScript = File.ReadAllText(path);
}
// check current customers role
var customerRole = customer.CustomerRoles.Where(x => x.Name == "Guests").FirstOrDefault();
if (customerRole != null)
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngageNewsLetter.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
// get NewsLetter Script file
Stream newsLetterScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.NewsLetter.js");
if (newsLetterScriptFile != null)
using (StreamReader reader = new StreamReader(newsLetterScriptFile))
{
newsLetterScript = reader.ReadToEnd();
}
}
else
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngage.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
}
var topicBody=string.Empty;
// get topic from settings
var topic = _setting.TopicName;
if (!string.IsNullOrEmpty(topic))
{
// get topic by system name
var topicRecord = _topicService.GetTopicBySystemName(topic);
if(topicRecord != null)
{
topicBody = topicRecord.Body;
}
}
// replace new line with slash and double coute with single coute
popupEngageView = popupEngageView.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
topicBody = topicBody.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
// append script
sb.Append("<script type=\"text/javascript\" src=\"/wwwroot/lib/jquery-1.10.2.min.js\">\n\t");
sb.Append(bioepEngageScript);
sb.Append(popupEngageScript);
sb.Append("$(\"" + popupEngageView + "\").insertAfter(\".newsletter\");");
sb.Append("$('.popupengage_popupmsg').html(\"" + topicBody + "\");");
sb.Append(newsLetterScript);
sb.Append("</script>\n");
var bytes = Encoding.ASCII.GetBytes(sb.ToString());
filterContext.HttpContext.Response.Body.WriteAsync(bytes,0, bytes.Length);
}
}
}
#endregion
file append in perfect way but it append script in top of the page before jquery. and that script append by string builder.Popup js example
if u are using jquery, make sure it is included before the script files that use jquery functionality;
For ex: if u have a js file named 'main.js' which has includes a line like $().forEach then your order of inclusion in the html file should be
<script>jquery.js </scrpt>
<script>main.js </scrpt>

send value to specific User in SignalR

I have 4 textboxes that are filling in same time after user push send button Using SignalR. In one part I am sending textbox values to all users and this is working. But when I try to send the values to specific user, after pushing the button, all textboxes get empty.
This is the code that is working, sending values to all users:
This is Hub:
public void Send(string loanType, string loanAmount, string interestRates, string payment)
{
User sender = GetUser(Context.User.Identity.Name);
var username = sender.Name;
IEnumerable<string> connectionIds = sender.ConnectionIds;
//All connected clients.
Clients.All.broadcastMessage(loanType, loanAmount, interestRates, payment);
}
and this is js:
$('#sendmessage').click(function (e) {
sendPayment();
e.preventDefault();
});
function sendPayment() {
var msgValue = $msgTxt.val();
var loanType = $('#txtLoanType').val();
var loanAmount = $('#txtLoanAmount').val();
var interestRates = $('#txtInterestRates').val();
var payment = $('#txtPayment').val();
if (loanType !== null && loanType.length > 0 && loanAmount !== null && loanAmount.length > 0 && interestRates !== null && interestRates.length > 0
&& payment !== null && payment.length > 0) {
if (viewModel.isInPrivateChat()) {
$.connection.hub.start();
chatHub.server.send(msgValue, viewModel.privateChatUser(), $('#txtLoanType option:selected').val(), $('#txtLoanAmount').val(), $('#txtInterestRates').val(), $('#txtPayment').val());
}
else {
// Call the Send method on the hub.
chatHub.server.send($('#txtLoanType option:selected').val(), $('#txtLoanAmount').val(), $('#txtInterestRates').val(), $('#txtPayment').val());
}
}
chatHub.client.broadcastMessage = function (loanType, loanAmount, interestRates, payment) {
$('#txtLoanType').val(loanType);
$('#txtLoanAmount').val(loanAmount);
$('#txtInterestRates').val(interestRates);
$('#txtPayment').val(payment);
};
but when I try to send values to specific user it is not working: as I am debussing the C# code is working I thing the problem is in JS:
this is C# method that send values of text boxes to specific user:
public void Send(string message, string to, string loanType, string loanAmount, string interestRates, string payment)
{
User receiver;
if (Users.TryGetValue(to, out receiver))
{
User sender = GetUser(Context.User.Identity.Name);
IEnumerable<string> allReceivers;
lock (receiver.ConnectionIds)
{
lock (sender.ConnectionIds)
{
allReceivers = receiver.ConnectionIds.Concat(sender.ConnectionIds);
}
}
foreach (var cid in allReceivers)
{
Clients.Client(cid).broadcastMessage(new { message = message, isPrivate = true, loanType = loanType,
loanAmount = loanAmount,
interestRates = interestRates,
payment = payment
});
}
}
}
it will call the Private part in JS file that is :
if (viewModel.isInPrivateChat()) {
$.connection.hub.start();
chatHub.server.send(msgValue, viewModel.privateChatUser(), $('#txtLoanType option:selected').val(), $('#txtLoanAmount').val(), $('#txtInterestRates').val(), $('#txtPayment').val());
The function signatures do not match. There are different number of paramerters, they have to match exactly or the javascript function will never be called, it looks like you are trying use the parameters for the send function, when you are calling the broadcastMessage function.
In the JavaScript for the user you are looking for:
function (loanType, loanAmount, interestRates, payment)
But you are sending:
broadcastMessage(new { message = message, isPrivate = true, loanType = loanType,
loanAmount = loanAmount,
interestRates = interestRates,
payment = payment
})

Use CAPICOM in Server Side

I have a code in .net for sign in client side and verify in server side.
And I must convert my code in asp classic.
In .net code on client side I sign with capicom by javascript.
My code:
<script type="text/javascript">
// Some needed constants
CAPICOM_CURRENT_USER_STORE = 2;
CAPICOM_STORE_OPEN_READ_ONLY = 0;
CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
CAPICOM_ENCODE_BASE64 = 0;
function Authenticate() {
try {
var challenge = document.getElementById("<%=hid_Challenge.ClientID %>");
var response = document.getElementById("<%=hid_Response.ClientID %>");
// Open windows certificate store
var store = new ActiveXObject("CAPICOM.Store");
store.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);
// Show personal certificates which are installed for this user
var certificates = store.Certificates.Select("KeyA3 Sample PKI Authentication", "Please select a certificate to authenticate.");
// Proceed if any certificate is selected
if (certificates.Count > 0) {
var signer = new ActiveXObject("CAPICOM.Signer");
signer.Certificate = certificates.Item(1);
var timeAttrib = new ActiveXObject("CAPICOM.Attribute");
timeAttrib.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
var date = new Date('<%=DateTime.Now.ToString("F", new System.Globalization.CultureInfo("en-US")) %>');
timeAttrib.Value = date.getVarDate();
signer.AuthenticatedAttributes.Add(timeAttrib);
var signedData = new ActiveXObject("CAPICOM.SignedData");
signedData.Content = challenge.value;
response.value = signedData.Sign(signer, true, CAPICOM_ENCODE_BASE64);
return true;
}
return false;
}
catch (e) {
alert(e.description);
return false;
}
}
</script>
And
I check signed data in this code:
Byte[] signedData;
ContentInfo content;
SignedCms signed;
if (hid_Response.Value == null)
throw new ArgumentNullException("Response");
signedData = Encoding.Unicode.GetBytes(Session["Challenge"].ToString());
content = new ContentInfo(signedData);
signed = new SignedCms(content, true);
signed.Decode(Convert.FromBase64String(hid_Response.Value));
// Set the parameter to 'true' if you want the certificate not be checked.
signed.CheckSignature(true);
// Do further authentication and user mapping here.
// For example you could check some certificate parameters against your database.
// Here we only show the certificate information. Nothing checked here.
lbl_Message1.Text = "Authenticated successfully.";
lbl_Message1.Visible = true;
Dictionary<String, String> certProps = new Dictionary<String, String>();
certProps.Add("Subject", signed.Certificates[0].Subject);
certProps.Add("Issuer", signed.Certificates[0].Issuer);
certProps.Add("Valid From", signed.Certificates[0].NotBefore.ToString());
certProps.Add("Valid To", signed.Certificates[0].NotAfter.ToString());
certProps.Add("Friendly Name", signed.Certificates[0].FriendlyName);
certProps.Add("Version", signed.Certificates[0].Version.ToString());
certProps.Add("Serial Number", signed.Certificates[0].SerialNumber);
certProps.Add("Thumbprint", signed.Certificates[0].Thumbprint);
gvCertificate.DataSource = certProps;
gvCertificate.DataBind();
gvCertificate.Visible = true;
But I must run this code in asp classic
I successfully sign my data in client side by javascript.
And I want to verify data in server side by VBSCRIPT OR JAVASCRIPT.
Is any way?
Thanks
I found answer.
It will be helpful.
Dim verification
Set verification = Server.CreateObject("CAPICOM.SignedData")
verification.Verify signed_Data, false, 0
For Each Certificate In verification.Certificates
subject = Certificate.SubjectName
Next
If Err.Number <> 0 Then
result = Err.Description & Hex(Err.Number)
Else
result = "Signature is OK"
End If

MVC3 and custom client-side validation messages

I have unobtrusive client-side validation setup for my page. The error messages are returned from our database. For one of the validation messages I needed to add parameters so I can format it with particular values. This works fine server side but I obviously haven't got access to some of these values when the GetClientValidationRules method is first setup. Because of this it looks like I'm going to have to build up the error message in my client-side code but I have no idea on how to do this as you simply return true or false in the jQuery.validator.addMethod.
So what I basically need to be able to do is set ErrorMessage to string.Empty in GetClientValidationRules method, and then in my clinet-side code which is doing the validation be able to return whatever message I want.
Here is the client-side code being wired up in MVC 3.
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "maximumdatecoverrequired",
ErrorMessage = string.Empty,
};
rule.ValidationParameters.Add("maxdate", DateTime.Now.AddDays(Settings.Default.MaximumDateCoverRequiredDaysInFuture).ToString("yyyy/MM/dd"));
return new[] { rule };
}
Here is my client-side code to validate against this particular property.
jQuery.validator.addMethod("maximumdatecoverrequired", function (value, element, params) {
var maxDate = new Date(params["maxdate"]);
var day = maxDate.getDate();
var month = maxDate.getMonth() + 1;
var year = maxDate.getFullYear();
var dateCoverRequired = new Date(value).toString('yyyy/MM/dd');
maxDate = maxDate.toString('yyyy/MM/dd');
if (value > maxDate) {
$("input#DateCoverRequired_Day").val(day);
$("select#DateCoverRequired_Month").val(month);
$("input#DateCoverRequired_Year").val(year);
return false;
}
return true;
});
How do I return a custom message in my client-side code?
Let me give you an example of how to do this. The example I'll choose is registering a new user and checking for their name.
What we're going to do is allow the user to choose a UserName and, if it already exists in the database, we won't let them have it and will make a suggestion.
To do this we'll use Remote validation which points to an ActionMethod in our controller.
Register Model
public class RegisterModel
{
//This is the one I'm giving you the code for...
[Required]
[RegularExpression(#"(\S)+", ErrorMessage = "Username cannot contain spaces.")]
[Remote("CheckUserName", HttpMethod="POST")]
[Display(Name = "Username")]
public string UserName { get; set; }
// You can do this one yourself :-)
[Required]
[Remote("CheckEmailAddress", ErrorMessage="{0} already has an account, please enter a different email address.", HttpMethod="POST")]
[DataAnnotationsExtensions.Email(ErrorMessage="{0} is not a valid email address.")]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
ActionMethod (the Remote method referenced by the model)
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public JsonResult CheckUserName(string userName, Guid? userId = null)
{
if (userName != null || userName.Length > 2)
{
var users = Membership.FindUsersByName(userName);
if (users.Count == 0)
{
return Json(true);
}
else
{
if ((users[userName].ProviderUserKey as Guid?) == userId)
{
return Json(true);
}
else
{
string suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available.", userName);
// Maybe this is a bit feeble, but it will loop around (inefficiently) and suggest a new username with a number on the end. EG Tom is not available. Try Tom37
for (int i = 1; i < 100; i++)
{
string altCandidate = userName + i.ToString();
if (Membership.FindUsersByName(altCandidate).Count == 0)
{
suggestedUID = String.Format(CultureInfo.InvariantCulture, "{0} is not available. Try {1}.", userName, altCandidate);
break;
}
}
// This is the important bit. I am returning a suggested UserName
return Json(suggestedUID, JsonRequestBehavior.AllowGet);
}
}
}
else
{
return Json(true);
}
}
I think this is pretty cool, because the regular expression makes sure there are no spaces and then (if it's okay) it's submitted to the remote method which checks the database.

Categories