Using jquery with expiry dates - javascript

Can I please get any help finishing this code I did for my website. I'm using jquery and what this code does is its checking the recert date (expiry date) of an application first before a customer can re-apply again, so basically they can only re-apply within 4 weeks of their current application expiry date.
e.g. if a person application expires Aug 31 2016 that means they can only re-apply from Aug 3 2016 to Aug 31 2016 with 4 weeks to be exact. An application last for 3 years.
I provided my code and its working but I don't know if this is the right conditions and all it does is just hide the apply button if expiry date is still not up.
$(document).ready(function(){
var current = new Date();
var expiry = new Date($("#mcs_nextrecertdate").val());
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").hide();
}
EDIT: Im testing the codes I receive from the answers based on these dates first can re-apply with 27 august 2016 and the second is a date that can't re-apply yet 20 July 2019

Given your question and explanation of your problem, I'd like to point out a few observations I've made
1. Date validation
var expiry = new Date($("#mcs_nextrecertdate").val());
Whatever #mcs_nextrecertdate is, I'll assume you've already made sure that this "input" element's value is correctly formatted. Otherwise you'll get a JS script error and the whole thing will break
2. Incorrect logic
Based on your explanation, a user can only re-certify WITHIN 4 weeks of the current application's expiry date. I'll assume that #NextButton is a submit button that triggers the new application. Based on that, this expression is wrong...
if(current.getTime() > expiry.getTime()){...}
because you're telling your app to allow users to apply for a certification AFTER the current application has expired, NOT WITHIN 4 weeks after expiration, in other words, users can ONLY re-apply after they're application expired...not before.
3. Server validation
This is just an assumption. I'll also assume this "client-side logic" is just to offer a good user experience of your app and that you are running proper server-side validation otherwise advanced users like me can easily bypass client-side validation, cheat/hack these "constraints" and even bring your application data to an inconsistent state.
Correct Logic
In order to make sure users can re-apply within 4 weeks prior to the current expiry date you need to do the following...
var now = new Date();
var expiry = new Date($("#mcs_nextrecertdate").val());//assuming this has a valid date
var startValidAppDate = new Date($("#mcs_nextrecertdate").val());
//set valid application dates
startValidAppDate.setTime(expiry.getTime() - (7 * 4 * 24 * 60 * 60 * 1000));//4 weeks to milliseconds
if(now < expiry && now > startValidAppDate){
//ok to apply
$("#NextButton").show();
}
Again, ALWAYS make sure you have strong validation on the server. Here's a working snipper...
$(function(){
$('#txtExpiryDateParent').datetimepicker({
format: "YYYY-MM-DD"
});
$("a").click(function(){
var now = new Date();
var expiry = new Date($("#txtExpiryDate").val());
var startValidAppDate = new Date($("#txtExpiryDate").val());
//set valid application dates
startValidAppDate.setTime(expiry.getTime() - (7 * 4 * 24 * 60 * 60 * 1000));//4 weeks to milliseconds
if(now < expiry && now > startValidAppDate){
$(".info.bg-success").show();
$(".info.bg-error").hide();
}
else{
$(".info.bg-success").hide();
$(".info.bg-error").show();
}
});
});
form{
background-color:#eee;
max-width:500px;
padding:30px;
margin:30px;
}
.info{
padding:20px;
border-radius:3px;
text-align:center;
margin-bottom:20px;
display:none;
}
.bg-success{
background-color:#5cb85c !important;
}
.bg-error{
background-color:#d9534f !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<form class="center-block">
<div class="info bg-success">You're good to re-certify</div>
<div class="info bg-error">You can't certify right now</div>
<div class="form-group">
<label for="txtExpiryDate">Expiry Date</label>
<div class='input-group date' id='txtExpiryDateParent'>
<input id="txtExpiryDate" type='text' name="ExpiryDate" class="form-control"
placeholder="Expiry date..." />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<a class="btn btn-default" href="javascript:void(0)">Validate</a>
</form>

Best practices in client-side is to remove your element NOT hide it .
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").remove();
}
Ans Best Practices in server-side are to check expiration date there and render HTML without #NextButton element.

When in doubt, always do testing:
$(document).ready(function(){
var current = new Date();
//var expiry = new Date("August 1, 2014");
var expiry = new Date("August 13, 2017");
if(current.getTime() > expiry.getTime()){
$("#NextButton").show();
}
else {
$("#NextButton").hide();
}
});

Related

Is there a way to get the date and time a user last changed their password in Google Workspace

We are moving away from AD and going to Google Work space as our LDAP service. One of my tasks are to reproduce some tools that we have on AD to Google Workspace. One of those tools is the ability to warn a user 14 days before a password is about to expire then 7 days before and send us (IT admins) a warning 4 days before to catch it before they get locked out. So I have created this tool in PowerShell on windows and LDAP and I am trying to use Google App Scripts to do this. I have learned that the Directory API does not expose this metadata on the user (https://developers.google.com/admin-sdk/directory/v1/guides/manage-users) and I have to use the Admin Report API and search the logs for an eventName called CHANGE_PASSWORD and then build an array of user email address and the last time they changed their password.
I have got this successfully working to show me a HTML output of email address and how many days left till their password expires in a table that is generated on demand when you load the web app, but I noticed we have 120 users in our Org and only 78 users show up on the list. So then I realized that the reports section of Google Admin reports only stores 6 months worth of logs. To me the reports section is not a reliable source to determine when the user last changed their password. Does anyone have any other ideas as to how I can accurately get the date a Google Workspace user last changed their password? Here is what I currently have if anyone wants to build on this:
Please note you must add the Admin SDK API service to your script and the user running the script my have the role for reports on your domain. This is not polished code but just a proof of concept so be gentle with your replies and comments about my sloppy code
code.gs
const maxPasswordAge = 90;
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function getListOfUsers() {
const userKey = 'all';
const applicationName = 'admin';
const optionalArgs = {
eventName: 'CHANGE_PASSWORD'
};
const logs = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
const activities = logs.items;
if (activities && activities.length > 0) {
var passwordLastChanged = new Object();
for (i = 0; i < activities.length; i++) {
const activity = activities[i];
const key = activity.events[0].parameters[0]['value'];
const value = activity.id.time;
// If the key does not exist then add it
if (!passwordLastChanged.hasOwnProperty(key)) {
passwordLastChanged[key] = value;
}
}
} else {
Logger.log('No results found.');
}
// You will now have an object with emailaddress:Date last Changed
const todaysDate = new Date();
// Change the date to a number of days till it expires from today's date
for (const [key, value] of Object.entries(passwordLastChanged)) {
const dateLastChange = new Date(value);
const milliBetweenDate = todaysDate - dateLastChange;
const diffInDays = milliBetweenDate / (1000 * 3600 * 24);
passwordLastChanged[key] = (maxPasswordAge - diffInDays).toFixed(1);
}
// Change the object to a sorted array based on the days left till password expires
const entries = Object.entries(passwordLastChanged);
const sorted = entries.sort((a, b) => a[1] - b[1]);
return sorted;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<style type="text/css">
body {background-color: gray;}
.tg {border-collapse:collapse;border-spacing:0;margin:0px auto;}
.td {border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px; overflow:hidden;padding:10px 5px;word-break:normal; color: floralwhite;}
.col1, .col2, .col3 {text-align:left;vertical-align:top}
.col4, .col5 {text-align:center;vertical-align:top}
</style>
<table id="myTable" class="tg">
<tbody>
<tr>
<td class="col3">Email</td>
<td class="col5">Days Left</td>
</tr>
</tbody>
</table>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(addUsersToTable).getListOfUsers();
});
function addUsersToTable(userArray) {
for (var i = 0; i < userArray.length; i++) {
$('#myTable > tbody:last-child').append('<tr><td class="col3">' + userArray[i][0] + '</td><td class="col5">' + userArray[i][1] + '</td></tr>');
}
}
</script>
</body>
</html>
So yes , 6 months is the maximum they keep the logs. If you are on the Enterprise SKU (which Is unlikely with 120 users) you can export logs to Bigquery indefinably and Query that. https://support.google.com/a/answer/9079365?hl=en If you have something else that is able to ingest the logs you can do that too.
However , I did something for the suspension date as that date is not set in a user field either.
You are going to need 2 processes.
Create a custom schema attribute for your password date option.
Have a process that routinely scrapes the audit logs. Say everyday you look for password changes in the past 24 hours. You then set the value on the custom schema attribute accordingly.
You second process will monitor that custom schema attribute and do your alerting to users.
To start I had to make an assumption. All users that didn't meet existing criteria would have a fixed date set. Moving forward this new process would ensure everything is inline.

JavaScript to show <div> after a certain date

I believe this is a relatively simple question (a JavaScript noob here), but I can't seem to find a thread for this particular date function. I am doing website migration for an academic society from a PHP-based site to a drupal CMS. Some of the PHP has obviously broken and I'm trying to replace simple scripts with Javascript. One issue that is giving me a lot of trouble is how to get a text to appear only AFTER a certain date. In PHP my functioning code is:
<?php if (date('YmdH') > 2018011710 ) { ?>
<p class="error">Please note that the deadline for submitting proposals has passed.</p>
<?php } ?>
So I need something in JavaScript to do the same. Here is what I came up with (I apologize in advance for my sloppy code as I'm a beginner with JavaScript):
First CSS to hide the DIV:
<style type="text/css">
.DateDiv { display: none;}
</style>
Then the div itself:
<div class="DateDiv">
<h3>Please note that the deadline for submitting proposals has passed.</h3>
</div>
Finally, my JavaScript, which is not working:
<script>
$(document).ready(function() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
// show only if current date is after January 16, 20018
if (today > 0, 16, 2018) {
$(".DateDiv").show();
}
});
</script>
If anyone could help me sort this out I would be very grateful. If I'm going about this in a manner that is more complicated than it needs to be I'd also appreciate any advice.
Thanks in advance.
PS: I am not asking to compare two dates, but to display a text after a certain date.
you just might want to do something like this:
if (new Date() >= new Date(2018, 0, 16))
months always start at 0 while days start at 1. don't ask why.
this is how the constructor is defined:
new Date(year, monthIndex [, day [, hour [, minutes [, seconds [, milliseconds]]]]]);
just go here for in-depth details about Date()
//show only if current date is after January 16, 20018
var date_to_check_with = new Date("20180116").getTime();
//.getTime() will give time in milliseconds (epoch time)
var current_date = new Date().getTime();
console.log(date_to_check_with < current_date);

My JS file won't load on my Chrome web application

I'm writing a Chrome web application and am trying to load a clock onto it, but this is not working. The HTML & CSS files are showing up but not the JS, meaning that the application just looks like an empty box.
I would really appreciate your help - thank you very much!
Here is my popup.html file:
<!DOCTYPEhtml>
<link rel="stylesheet" type="text/css" href="popup.css">
<title>Your Personal Homepage</title>
<script src="popup.js"></script>
<script src="clock.js"></script>
</head>
<body>
<div id="clock" class="light">
<div class="display">
<div class="weekdays"></div>
<div class="ampm"></div>
<div class="alarm"></div>
<div class="digits"></div>
</div>
</div>
<!-- JavaScript Includes -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>
</body>
</html>
And here is my clock.js file:
$(function(){
// Cache some selectors
var clock = $('#clock'),
alarm = clock.find('.alarm'),
ampm = clock.find('.ampm');
// Map digits to their names (this will be an array)
var digit_to_name = 'zero one two three four five six seven eight nine'.split(' ');
// This object will hold the digit elements
var digits = {};
// Positions for the hours, minutes, and seconds
var positions = [
'h1', 'h2', ':', 'm1', 'm2', ':', 's1', 's2'
];
// Generate the digits with the needed markup,
// and add them to the clock
var digit_holder = clock.find('.digits');
$.each(positions, function(){
if(this == ':'){
digit_holder.append('<div class="dots">');
}
else{
var pos = $('<div>');
for(var i=1; i<8; i++){
pos.append('<span class="d' + i + '">');
}
// Set the digits as key:value pairs in the digits object
digits[this] = pos;
// Add the digit elements to the page
digit_holder.append(pos);
}
});
// Add the weekday names
var weekday_names = 'MON TUE WED THU FRI SAT SUN'.split(' '),
weekday_holder = clock.find('.weekdays');
$.each(weekday_names, function(){
weekday_holder.append('<span>' + this + '</span>');
});
var weekdays = clock.find('.weekdays span');
// Run a timer every second and update the clock
(function update_time(){
// Use moment.js to output the current time as a string
// hh is for the hours in 12-hour format,
// mm - minutes, ss-seconds (all with leading zeroes),
// d is for day of week and A is for AM/PM
var now = moment().format("hhmmssdA");
digits.h1.attr('class', digit_to_name[now[0]]);
digits.h2.attr('class', digit_to_name[now[1]]);
digits.m1.attr('class', digit_to_name[now[2]]);
digits.m2.attr('class', digit_to_name[now[3]]);
digits.s1.attr('class', digit_to_name[now[4]]);
digits.s2.attr('class', digit_to_name[now[5]]);
// The library returns Sunday as the first day of the week.
// Stupid, I know. Lets shift all the days one position down,
// and make Sunday last
var dow = now[6];
dow--;
// Sunday!
if(dow < 0){
// Make it last
dow = 6;
}
// Mark the active day of the week
weekdays.removeClass('active').eq(dow).addClass('active');
// Set the am/pm text:
ampm.text(now[7]+now[8]);
// Schedule this function to be run again in 1 sec
setTimeout(update_time, 1000);
})();
Is there any way to make this show up?
Thank you!
Your clock.js uses jQuery but is loaded before jQuery is loaded. Include it after jQuery instead.
Chrome extensions and apps obey a Content Security Policy.
This disallows external scripts, so you should download the external files and put them in the same folder as your other scripts.

How can I get selected time and add class via jQuery?

My HTML is dynamic and like that:
<div class="date">
<strong>21</strong>
<span class="month">Jan</span>
<strong class="year">15</strong>
<span class="details"></span>
</div>
And I want get this time and print console via jQuery:
var selectedDate = $('.date');
console.log(selectedDate);
But result is not correct. How can I fix it?
EDIT:
Ok, I solve my problem with that:
console.log(selectedDate.text());
Now, I want add class if event is a past event.
if (selectedDate < now) {
$('.event').addClass('past');
}
But not any error or result.
Try this:
selectedDate = $(".date > .month").text() + " "
+ $(".date > strong:nth-child(1)").text() +
" 20"+ $(".date > .year").text();
console.log(selectedDate); // Jan 21 2015
You could, of course, re-arrange those to output the date according to the format you want -

reset rich:calendar value on jsf form using java script

I am trying to reset value of rich:calender input box via java script but couldnt do it any way at all. the UI of my form (snippet only) is...
<rich:calendar id="startDate" datePattern="dd MMM yyyy" value="#{classBean.startDate}" popup="true" onchanged="calcDuration();">
</rich:calendar>
the java script is
function calcDuration()
{
sdate =$('frm_course:startDate').component.getSelectedDateString("dd MMM
yyyy");
var currentdate = new Date();
var sdatecmp = new Date(sdate);
if(sdatecmp > currentdate)
{
alert('The Start Date is Greater than today!');
$('frm_viewCourseDetail:startDate').component.value = ""; // 1
document.getElementById('frm_course:startDate').value =""; // 2
}
}
None of the lines 1 and 2 resets the richcalender's value. Help is required here. thanks.
The calendar (and other components) is backed by a JavaScript object which has the methods you need.
Use either #{rich:component('startDate')} or RichFaces.$('startDate') to get a reference to that object and then call resetValue().
For other methods check the docs

Categories