Make server run function once per day - javascript

I have an object on my database containing rows with different dates + emails. I need the server to automatically check once every day or week if any of the listed dates are the current date, and if so send an email to that person. (Image of the object in backand below).
I have made an email "on demand action" at the server side logic and operations in backand, which works, but i have to trigger it manually. Instead i need the server to trigger it on a specific time.
Is this possible to do, and if so how?
A solution i was thinking of, is having a function which is looping through the object, checking dates and sending the emails. And then somehow make the server run this function once per day/week or something.

Cron solution is something we plan to add in the next few weeks, but in the meanwhile, we have a good FREE solution that let you do it.
The service is https://www.easycron.com.
You just need to specify the URL of the action, which you can get from the test action panel (after executing it in test mode).
To gain access to the action, you need to implement the basic authentication which means to use the masterKeyToken( Security & Auth--> Configuration) and an adminKey (Security & Auth--> Team--> click on the key icon near one of the Admins) like that:
https://masterKeyToken:adminKey#api.backand.com/1/objects/action/ObjectName1?name=YourActionName
To read more on Basic auth click here: http://docs.backand.com/en/latest/apidocs/security/#basic-authentication

Cronjobs are the way to go.
If your hoster does not support cronjobs you have no chance to do it well.
A quick google shows me that one.com MAY not support cronjobs. But I'm not sure.
Maybe ask the support.
If they does not I would choose a different hoster which is not shitty.
(Only a shitty hoster does not support crons. I'm not saying one.com is such hoster because I don't know).
If you don't want to and they don't offer crons you could use "Poor Mens Cron". It's a crappy hack from ancient times of the Internet.
You can google that because I wouldn't recommend.

Related

Get the users local time accurately

I am working on a project which primarily uses javascript, css, html5. I need to get the local time accurately no mater where the user is located to allow user to access a module on a particular date. Assume 1 September.
How do i get the users local time accurately?
Options:
1: Use JavaScript to get the users local time and use it.
problem: The user can manually change the date time settings of his system to change the date and access the module prematurely.
2: Use server date time to enable a module on a particular date.
problem: The server could be located anywhere eg: in U.S. and people in Australia will not be able to access the module unless the date in U.S is 1 September.
Is there any other option.
Is using client IP address a option?
well, the user's time/date info is not included in the http request header, so php will not automatically have that information. You can, as you said, use javascript to get the user's time similar to what was posted here: Determine a User's Timezone -- this is with pure javascript, if you use jquery or something similar to it, you can do it very easily.
if these are registered users however, you can allow them to set a timezone in their profile/settings, and then just use THAT setting, so even if they are traveling, they will always be set to the "home" timezone.
does that help?
First of all you should always assume user may fake any data calculated on his side. Therfore using server time is more reliable.
Using IP is an option - you can find services and databases that allow you to resolve IP to country its located in. Example: http://php.net/manual/en/book.geoip.php
Lastly - why do you want efectively differend release date for various countries? They can always use someone in other country to access module in their name.
If the user gives permission, and is using a supported browser, etc, you can get their location using navigator.geolocation.getCurrentPosition().
See developer.mozilla.org/en-US/docs/Web/API/Geolocation.getCurrentPosition for parameters and more info.
You can then use a service such as provided by geonames.org. Eg, http://api.geonames.org/timezone?lat=47.01&lng=10.2&username=demo . This returns the time at the given coords.
Update as per first comment: Of course you can never trust any data coming in from outside. But you can do things to raise levels of confidence. This wasn't meant to be a full stand-alone solution.

How "secure" is the ASP .NET Controller

I am still very new to the concepts and design of ASP .NET's MVC and AJAX and I was wondering how secure the Controller is to unwanted user's when webdeployed.
I ask because for fun I made a little admin panel that requires a user name and password. Once input is entered the information is AJAX submitted to a ActionResult method in the Controller that just compares the strings to see if they match, then returns the response back to the AJAX.
My question is, how easy is it for someone to get into my Controller and see the hard-coded password?
No professional-type person will ever try to break into this, as it is a free site for a university club, but I want to make sure that the average Computer Science student couldn't just "break in" if they happen to "rage" or get mad about something (you never know! haha).
Question: Is having a password validation within the Controller "decently" secure on a ASP .NET MVC web-deployed application? Why or why not?
Here is the actual code in case the use of it matters for the answer (domain is omitted for privacy)
Note: I understand this use of Javascript might be bad, but I am looking for an answer relative to AJAX and Controller security of the password check.
View (Admin/)
//runs preloadFunc immediately
window.onpaint = preloadFunc();
function preloadFunc() {
var prompting = prompt("Please enter the password", "****");
if (prompting != null) {
$.ajax({
url: "/Admin/magicCheck",
type: "POST",
data: "magic=" + prompting,
success: function (resp) {
if (resp.Success) {
//continue loading page
}
else {
//wrong password, re-ask
preloadFunc();
}
},
error: function () {
//re-ask
preloadFunc();
}
});
}
else {
// Hitting cancel
window.stop();
window.location.replace("google.com");
}
}
Controller (ActionResult Snippet)
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "pass")
{
success = true;
}
else
{
success = false;
}
return Json(new { Success = success });
}
Again I am new to MVC and AJAX, let alone anything dealing with security so I am just wondering how secure the Controller is, specifically on webdeploy for this simple password setup.
During normal operation, there is no concern as your code is compiled, the DLL prevented from being served, and there is no way for the browser to request the controller to divulge its own code.
However, it is not impossible (but quite rare) that unforeseen bugs, vulnerabilities, or misconfigurations of the server could lead to the server divulging compiled code, web.config, etc., whereby someone could disassemble the code (IL is easily decompiled) and reveal your secret.
More worrisome would be someone having physical access to the server just grabbing the binaries directly and disassembling to find your secret.
Another thing to consider is who, during normal situations, might see that secret and whether or not they should know it. A developer, tester, or reviewer may be allowed to write or inspect code, but you may not want them to know the secret.
One way to handle this is not store secrets in plain text. Instead, create a hash of the valid value, then update your application to hash the user's input in the same manner, and compare the results. That way if the user ever gets your source code, they can't read the original plain text value or even copy/paste it into your UI. You can roll your own code to do the hashing, use the FormsAuthentication API, or something else.
Finally, do not rely on client-side enforcement of security. You can check security on the client side to have the UI react appropriately, but all server-side requests should be doing checks to make sure the user's security claims are valid.
The question really goes out of scope from here, regarding how to manage identities, passwords, and make security assertions. Spend a little time looking through the myriad articles on the subject. Also, the Visual Studio ASP.NET project templates include a lot of the security infrastructure already stubbed out for you to give you a head start.
Never leaving things to chance is an important policy. Learning about ASP.NET and MVC's various facilities for authentication and authorization is a worthwhile effort. Plus, there are numerous APIs you can plug in to do a lot of the heavy lifting for you.
As has already been pointed out if you can get a hold of the binaries for an app (or for that matter ANY .NET application not just MVC) then it's definately game over.
Just sat in front of me here and now I have 3 applications that make it child's play to see what's inside.
Telerick - Just Decompile
IL-Spy
Are both freely downloadable in seconds, and the former of the two will take an entire compiled assembly, and actually not just reverse engineer the code, but will create me a solution file and other project assets too, allowing me to load it immediately back into Visual Studio.
Visual Studio meanwhile, will allow me to reference the binaries in another project, then let me browse into them to find out their calling structure using nothing more than the simple object browser.
You can obfuscate your assemblies, and there are plenty of apps to do this, but they still stop short of stopping you from de-compiling the code, and instead just make the reverse engineered code hard to read.
on the flip side
Even if you don't employ anything mentioned above, you can still use command line tools such as "Strings" or editors such as "Ultra Edit 32" and "Notepad++" that can display hex bytes and readable ASCII, to visually pick out interesting text strings (This approach also works well on natively compiled code too)
If your just worried about casual drive by / accidental intrusions, then the first thing you'll want to do is to make sure you DON'T keep your source code in the server folder.
It's amazing just how many production MVC sites Iv'e come accross where the developer has the active project files and development configuration actually on the server that's serving live to the internet.
Thankfully, in most cases, IIS7 is set with sensible defaults, which means that things like '*.CS' files, or 'web.config' files are refused when an attempt is made to download them.
It's by no means however an exact science, just try the following link to see what I mean!!
filetype:config inurl:web.config inurl:ftp
(Don't worry it's safe, it's just a regular Google Search link)
So, to avoid this kind of scenario of leaking documents, a few rules to follow:
Use the web publishing wizard, that will ensure that ONLY the files needed to run end up on the server
Don't point your live web based FTP root at your project root, in fact if you can don't use FTP at all
DO double check everything, and if possible get a couple of trusted friends to try and download things they shouldn't, even with a head start they should struggle
Moving on from the server config, you have a huge mountain of choices for security.
One thing I definitely don't advocate doing though, is rolling your own.
For years now .NET has had a number of very good security based systems baked into it's core, with the mainstay being "ASP.NET Membership" and the current new comer being "ASP.NET simple membership"
Each product has it's own strengths and weaknesses, but every one of them has something that the method your using doesn't and that's global protection
As your existing code stands, it's a simple password on that controller only.
However, what if I don't give it a password.
What happens if I instead, decide to try a few random url's and happen to get lucky.
eg: http://example.com/admin/banned/
and, oh look I have the banned users page up.
This is EXACTLY the type of low hanging entry point that unskilled script kiddies and web-vandals look for. They wander around from site to site, trying random and pseudo random URL's like this, and often times they do get lucky, and find an unprotected page that allows them to get just far enough in, to run an automated script to do the rest.
The scary part is, small college club sites like yours are exactly the type of thing they look for too, a lot of them do this kind of thing for the bragging rights, which they then parade in front of friends with even less skill than themselves, who then look upon them as "Hacking Heroes" because they broke into a "College Site"
If however, you employ something like ASP.NET membership, then not only are you using security that's been tried and tested, but your also placing this protection on every page in your site without having to add boiler plate code to each and every controller you write.
Instead you use simple data annotations to say "This controller is Unprotected" and "This one lets in users without admin status" letting ASP.NET apply site wide security that says "NO" to everything you don't otherwise set rules for.
Finally, if you want the last word in ASP.NET security, MVC or otherwise, then go visit Troyhunt.com I guarantee, if you weren't scared before hand, you will be afterwards.
It looks like you are sending a password via AJAX POST. To your question, my answer would be that you should consider using SSL or encrypt the password prior to sending it via POST. See this answer for an example and explanation SSL Alternative - encrypt password with JavaScript submit to PHP to decrypt
As HackedByChinese said, the actual code being stored in your compiled files (DLL) wouldn't be too big of a deal. If you want to be extra paranoid, you can also store the password in your web.config and encrypt it there. Here's an example and explanation of that How to encrypt username and password in Web.config in C# 2.0
This code is not secure at all. Your JavaScript code can be replaced with EVERYTHING user wants. So someone can just get rid of your preloadFunc. Average computer sience student will execute this code directly from console:
if (resp.Success) {
//continue loading page
//this code can be executed by hand, from console
}
And that will be all when it comes to your security.
Authentication and authorization info should go to server with every request. As a simple solution, you could use FormsAuthentication, by calling
FormsAuthentication.SetAuthCookie("admin")
in /Admin/magicCheck, only if password is correct.
Then you should decorate data retrieval methods with [Authorize] attribute to check if cookie is present.
Using SSL to secure communication between browser and server would be wise too, otherwise password travels in clear text.

Monitoring User Sessions to Prevent Editing Conflict

I'm working on something similar to a pastebin (yeah, it's that generic) but allowing for multiple user editing. The obvious problem is that of multiple users attempting to edit the same file. I'm thinking along the lines of locking down the file when one user is working on it (it's not the best solution, but I don't need anything too complex), but to prevent/warn the user I'd obviously need a system for monitoring each user's edit sessions. Working with database and ajax, I'm thinking of two solutions.
The first would be to have the edit page ping the server at a arbitrary interval, say a minute, and it would update the edit session entry in the db. Then the next time a script request to edit, it checks for the most recent ping, and if the most recent was another arbitrary time ago, say five minute, then we assume that the previous user had quited and the file can be edited again. Of course, the problem with this method is that the assumption that the previous user had quited is simply an assumption. He could be having flaky wi-fi connection and simply dropped out for ten minutes, all the time with the window still open.
Of course, to deal with this problem, we'd have to have the server respond to new request from previously closed sessions with an error, telling the client side to point out to the user that his session has ended, and then deal with it by, say, saving it as another file on the server and asking the user to manually merge it, etc. It goes without saying that this is rather horrible for the end user.
So I've came around to think of another solution. It may also be possible to get a unload event to fire when the user's session ends, but I cannot be sure whether this will work reliably.
Does anybody has any other, more elegant solution to this problem?
If you expect the number of concurrent edits to the file to be minor, you could just store a version number for the file in the db, and when the user downloads the file into their browser they also get the version number. They are only allowed to upload their changes if the version number matches. First one to upload wins. When a conflict is detected you should send back the latest file and the user's changes so that the user can manually merge in the changes. The advantage is that this works even if it's the same user making two simultaneous edits. If this feature ends up being frequently used you could add client-side merging similar to what a diff tool uses (but you might need to keep the old revisions in that case).
You're probably better off going for a "merge" solution. Using this approach you only need to check for changes when the user posts their document to the server.
The basic approach would be:
1. User A gets the document for editing, document is at version 1
2. User B gets the document for editing, document is at version 1
3. User B posts some changes, including the base version number of 1
4. Server updates document, document now at version 2
5. User B posts some changes, including the base version number of 1
6. Server responds saying document has changed since the user starts editing, and sends user the new document, and their version - user will then need to perform any merging of their changes into document version 2, and post back to the server. User is essentially now editing document version 2
7. User A posts some changes, including the version number of 2
8. Server updates the document, which is now at version 3
You can still do a "ping" every minute, to get the current version number - you already know what version they're editing, so if a new version is available you can let them know and let them download the latest version to make their changes into.
The main benefit of this approach is that users never lock files, so you don't need any arbitrary "time-outs".
I would say you are on the right track. I would probably implement a hybrid solution:
Have a single table called "active_edits" or something like that with a column for the document_id, the user, and the last_update_time. Lets say your ping time is 1 minute and your timeout is 5 minutes. So a use-case would look like this:
Bob opens a document. It checks the last_update_time. If it is over 5 minutes ago, update the table with Bob and the current time. If it is not, someone else is working on the document, so give an error message. Assuming it is not being edited, Bob works on the document for a while and the client pings an update time every minute.
I would say do include a "finish editing" button and a onunload handler. Onunload, from what I understand can be flaky, but might as well add it. Both of these would send a single send-only post to the server saying that Bob is done. Even if Bob doesn't hit "finish editing" and onunload flakes out, the worst case is that another user would have to wait 5 more minutes to edit. The advantage is that if these normally work (a fair assumption) then the system works a bit better.
In the case you described where a Bob is on a bad wireless connection or takes a break: I would say this isn't a big deal. Your ping function should make sure that the document hasn't been taken over by someone else since Bob's last ping. If it has, just give Bob a message saying "someone else has started working on the document" and give them the option to reload.
EDIT: Also, I would be looking into window.onbeforeunload, not onunload. I believe it executes earlier. I believe this is the function website (slashdot included) use to allow you to confirm that you actually want to leave the page. I think it works in the major browsers except Opera.
As with this SO question How do you manage concurrent access to forms?, I would not try to implement pessimistic locking. It is simply too difficult to get working reliably in a stateless environment. Instead, I would use optimistic locking. However, in this case I used something like a SHA hash of the file to determine if the file had changed since the user last read from the file. For each request to change the file, you would run a SHA hash of the file bytes and compare it with the version you pulled when you first read the data. If had changed, you reject the change and either force the user to do their edits again (pulling a fresh copy of the file contents) or you provide a fancier conflict resolution.

how to do something like google-analytics

I need to make something like google-analytics, I mean that it has to be very simple to install and enables a comunication between 2 websites.
Let me explain the idea.
I'm developping an application (with ZF) where my clients will be online shops, OSCommerce only at the begining. Those shops need to get some info from my app's database, send me some info and propose to their clients to use my app's service.
What does the code needs to do:
if there is a certain $_GET param in the URL (that indicates that the user is coming from my site) -> starts a session in the shop and send me some info for my stats (IP, browser info, etc...)
if this user buys something during this sesion -> send me some info about the sale (total, id, ...)
during the checkout process (checkout-payment.php in OSC) give the possibility to the user (the shop's client who is also a member of my application) to insert his email+password from his my-application's account in order to get a discount in the order he's placing.
I know how to program all this, editing the shop's files, but my problem is that I have no idea about how to make it in the google-analytics way (give a small javascript to my customers to install in their store) and neither what to look for in google in order to find the information I need.
So, can anyone helps me to get in the right path?
Thanks in advance
Since you'll be needing to go cross-domain with this utility, you'll want to write your javascript piece for inclusion using JSONP. Your JSONP "call" could simply be made to some PHP script on your server by tacking on information obtained from window.location (like the query string, for example).
Maybe all you need is to give your customer an URL pointing to your js library? And than your library can work or better provide them with API to your service to get customer data etc.?
And yes - JSONP can help you with inter-domain comunication...

Propagate Permissions to Javascript

I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take.
Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low level as disabling certain context menu items). Of course, I still need to enforce the permissions server side.
So, I was wondering if anyone has any suggestions for the best way to
maintain the permissions and use them in server code
have easy access to the permissions in javascript
not have to make a round-trip request to the server for each individual permission
Thoughts?
If you have a clear set of permissions, like a "user level" or "user type", you could just pass the value down in a hidden field and access the value through the DOM. You could still do this if your permissions were more granular, but you would either have a lot of hidden fields or you would have to encode the information into XML or JSON or some other format.
You might set them as bit flags so that you could OR a single numeric value with a mask to see if the user had the permission for a specific activity. That would be very flexible and as long as you don't have more than 32 or so specific "rights", that would allow for any permutation of those rights in a very small package (basically an unsigned int).
For example:
0x00000001 //edit permission
0x00000002 //create new thing permission
0x00000004 //delete things permission
0x00000008 //view hidden things permission
.
.
.
0x80000000 //total control of the server and everyone logged in
Then a user with a permission of 0x000007 could edit, create, and delete, but nothing else.
In either case, I think you're on the right track - make the request once per page invocation, store the permissions in a global JavaScript data structure, and go from there. AJAX is nice, but you don't want to query the server for every specific permission all over your page. You would do it once on the page load, set up the presentation of your page and save the value in a global variable, then reference the permission(s) locally for event functions.
If you transmit the permission structure to the client as a JSON object (or XML, if you prefer), you can manipulate that object with the client-side code, and send it back to the server, which can do whatever it needs to validate the data and persist it.
I don't necessarily see it as the most "correct" solution, but would it be possible to keep all the permission stuff on the server side, and just serve the updated UI rather than some kind of JSON permissions system?
You'd have to make the decision based on how busy and intensive your app expects to be, but definitely a decision worth making either way
Encode them as JSON.

Categories

Resources