Last Login Date/Time

In an attempt to keep track of when users have last logged in, I've put together a script that sets the date&time a user accesses the home page (view_49).

The "all users" object (object_4) is expanded with a short text field called "last login" (field_43).

// Set date & time a user accesses the home page
// http://helpdesk.knackhq.com/support/solutions/articles/5000528001-working-with-the-logged-in-user#remote
$(document).on("knack-view-render.view_49", function(event, view) {
var user_rec_id=Knack.getUserAttributes().id;
var api_url="https://api.knackhq.com/v1/objects/object_4/records/"+user_rec_id;
var str=new Date().toString();
var data={field_43: str};

$.ajax({
url: api_url,
type: “PUT”,
headers: {“X-Knack-Application-Id”:Knack_App_ID,“X-Knack-REST-API-Key”:API_Key},
data: data,
success: function(data, textStatus, xhr) {
console.log("Date set: "+data.field_43);
},
error: function(xhr) {
console.log("Error ! Status: “+xhr.status+” "+xhr.statusText);
}
}); // ajax
});

 

So the script doesn’t actually track the last login but merely updates the “last login” field when a user accesses the home page. So is an indication only.

What are other people using to record last login ? Has anyone had more success ?

Cheers

Bart

It would be great if we could set record rules on the login form.

Per Sterling's comment (concern about the API key), this is how I could get around:

I wanted to record login history of users who viewed a certain table (view_1).

I made a new object called 'login history' containing short text field "user email" (field_100) and number field "time" (field_101).

Added a page with a form (view_2 in scene_2) creating a new record in 'login history' object (I've set this page not to be displayed in the menu).

------------------------------------------------------------------------------

$(document).on('knack-view-render.view_1', function (event, view, record) {

var d = new Date();
var ms = d.getTime(); //I found time format sometimes differs (e.g. dd/mm/yyyy vs mm/dd/yyyy) depending on the user, so getting the millisecond since 1970/01/01 was safer

var url = 'https://api.knack.com/v1/pages/scene_2/views/view_2/records/';

var data = {
  field_100: Knack.getUserAttributes().email,
  field_101: ms
};

$.ajax({
  url: url,
  type: 'POST',
  headers: {
    "X-Knack-Application-ID": ### APP ID ###,
    "Authorization": Knack.getUserToken(),
    "Content-Type":'application/json'
  },
  data: JSON.stringify(data),
  success: function(response) {
    console.log(JSON.stringify(response));
  },
  error: function(response) {
    console.log(JSON.stringify(response));
  }
});
});

We strongly recommend that you do not use object-based requests from any client-side code, including custom JavaScript added directly to your Knack apps, as this will expose your API key to anyone visiting your app. 

You can find more information about object-based requests here:
https://www.knack.com/developer-documentation/#object-based-requests

Does this work with SSO?

Hi, I tried implementing this with my own object_#, view_#, field_#, App ID #, and API Key # but it doesn't work. I know the API is being called because it the number of calls increments each time I refresh the view. It's just not putting the data into the field. Any suggestions on how to debug would be much appreciated! Edwin   

Tess, you replaced the ### by your own in this line, right?

headers: {"X-Knack-Application-Id":"###","X-Knack-REST-API-Key":"###"},

 

Joel

Hi Bart, I just tried this but didn't have any luck, any insights are much appreciated.  Thanks! Tess

 

// Set date & time a user accesses the home page
// http://helpdesk.knackhq.com/support/solutions/articles/5000528001-working-with-the-logged-in-user#remote
$(document).on("knack-view-render.view_17", function(event, view) {
var user_rec_id=Knack.getUserAttributes().id;
var api_url="https://api.knackhq.com/v1/objects/object_5/records/"+user_rec_id;
var str=new Date().toString();
var data={field_195: str};

$.ajax({
url: api_url,
type: "PUT",
headers: {"X-Knack-Application-Id":"###","X-Knack-REST-API-Key":"###"},
data: data,
success: function(data, textStatus, xhr) {
console.log("Date set: "+data.field_195);
},
error: function(xhr) {
console.log("Error ! Status: "+xhr.status+" "+xhr.statusText);
}
}); // ajax
});

I just wanted to tell you guys how much I appreciate you guys putting this information out there.  After over a year of use this suddenly became an urgent ask....and because of your willingness to put this out there, I implemented withing minutes.

 

Thank you!

Is your time zone set correctly In your app settings?

1 Like

Hi Tblizzard,

I was wondering if you ever got the +7h date issue figured out. I am trying to add a 'Last updated' date+time to my records following the instructions here: https://support.knack.com/hc/en-us/articles/231857848-Track-When-Records-are-Created-and-Updated. It works well except that the time is 3 hours into the future. That is, if I change a record at 2:30PM, it will be documented as 5:30PM. Any insights as to how to deal with this will be welcome.

Thanks!

Leeat

This is brilliant! Thank you for sharing Bart and Tblizzard! Works like a charm!

Love this! Here's how I used it to deactivate stale user accounts.

Instead of creating a string field I created a date/time field and also another date/time fields "Termed by Task Date". Then used a daily task to update each user's status to inactive if they haven't logged in for a while. I also created a separate task to run at the end of the day to email me if "Termed By Task Date" is today. This way I don't have to worry about stale accounts.


Resolved this by making the Last Login field a short text field instead of a date field. Modified the code to create a local string time with the seconds removed. In case someone else wants something like this, code is below.

 

// Set date & time a user accesses the home page
// http://helpdesk.knackhq.com/support/solutions/articles/5000528001-working-with-the-logged-in-user#remote
$(document).on("knack-view-render.view_1069", function(event, view) {
var user_rec_id=Knack.getUserAttributes().id;
var api_url="https://api.knackhq.com/v1/objects/object_9/records/"+user_rec_id;
var string=new Date().toLocaleString();
var resultArray=string.split(":");
var result=string.replace(":"+resultArray[2]," ")+resultArray[2].split(" ")[1];
var data={field_735: result};

$.ajax({
url: api_url,
type: “PUT”,
headers: {“X-Knack-Application-Id”:“APP ID HERE”,“X-Knack-REST-API-Key”:“API KEY HERE”},
data: data,
success: function(data, textStatus, xhr) {
console.log("Date set: "+data.field_735);
},
error: function(xhr) {
console.log("Error ! Status: “+xhr.status+” "+xhr.statusText);
}
}); // ajax
});

 

One more question, it posts a time that is 7+ hours ahead. I'm looking at the code (not familiar with this) and I don't see anything that would direct it to a different time frame. Considered it was maybe due to my system time (windows time) and that is the correct time. Any ideas?

i.e. last login posts as 8/5/2015 5:38pm (when it is 10:38am here), all other fields I have where a current date/time is inserted on submission of a form uses the correct time.

Forgot the " " around the app id, and api key. Working fine now.

Thanks Bart.

I’m not sure why it fails. I pasted your code “as is” (modifying keys of course), no probs in IE, FF, Chrome so I’m intrigued to what is causing this.

I get a debugger pause in knack.js (eval(js)) which is stating that there is an expected '}'.

See screenshot. I tried backing out all the js I have and only using your code, still get the error, remove yours and page loads fine.

At first glance, the syntax seems OK. If you use Chrome, use the console (F12) to see where it fails ?

Having an issue getting this to work. Pasted the code into the JavaScript section of the API & Code settings of Knack and made the changes needed to the object_#, view_#, field_#, App ID #, and API Key #. Entire application does not load.

 

// Set date & time a user accesses the home page
// http://helpdesk.knackhq.com/support/solutions/articles/5000528001-working-with-the-logged-in-user#remote
$(document).on("knack-view-render.view_1075", function(event, view) {
var user_rec_id=Knack.getUserAttributes().id;
var api_url="https://api.knackhq.com/v1/objects/object_9/records/"+user_rec_id;
var str=new Date().toString();
var data={field_735: str};

$.ajax({
url: api_url,
type: “PUT”,
headers: {“X-Knack-Application-Id”:###,“X-Knack-REST-API-Key”:###},
data: data,
success: function(data, textStatus, xhr) {
console.log("Date set: "+data.field_735);
},
error: function(xhr) {
console.log("Error ! Status: “+xhr.status+” "+xhr.statusText);
}
}); // ajax
});

 

view_1075 is my home page after the user logs in (the actual login is a scene).

object_9 is my “All Users” object.

field_735 is the added “Last Login” field to the “All Users” object_9.

App ID and API key removed from code, but they were copied from the API section of the Knack settings.

Any idea where I went wrong with this?

Thanks.

Todd