Should I notify user if link has been expired? - email

I'm creating logic for password recovery. User will submit request by providing their email address. Then email will be sent with more information that includes the link with the url parameter. This parameter is token created with ColdFusion createUUID() method. When user clicks on the link first thing to check is if url parameter exist then if it's valid token. The next step is to check if token exists in Database and pull Expiration value/timestamp. Here is example of my code:
<cfscript>
if (structKeyExists(url,"token") AND isValid("uuid", url.token) AND len(trim(url.token)) EQ 35){
cfstoredproc( procedure="ckToken", datasource=dsn ) {
cfprocparam( maxlength=35, null=!len(trim(url.token)), cfsqltype="cf_sql_varchar", dbvarname="#Token", value=trim(url.token) );
cfprocresult( name="Result" );
}
if( dateCompare(now(), Result.Expires, "s") == -1 ){
writeOutput("Link Valid Current: " & now() & " Expires: " & Result.Expires);
//include = "form.html";
}else{
writeOutput("Link Invalid Current: " & now() & " Expires: " & Result.Expires);
}
}else{
}
</cfscript>
If link is valid and not expired user will be directed to .html that has form with the password input field. If link has been expired I'm wondering should notify the user with the message or kick them back to the login page? I'm not sure if there is standard process for this kind of situation. If anyone have any suggestions please let me know.

Related

How to redirect in JAX-RS after a post to a get

I'm developing a simple login form (security is not a problem) where the user visits the page login inserts username and password and press send that POST these information to the page check.
Page check checks credential and, if everything is OK, creates cookie and redirect to page home, otherwise redirects to page login.
I use the following redirect:
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
This redirects from check (#POST method) to home (#POST method), I just wanna to redirect to home (#GET method).
Important note: I'm a newbie of JAX and what I would like to create is a RESTful service. Are redirects a correct way to implement a REST service?
Now I'll show you small slices of code hoping:
check Page
#POST
#Produces(MediaType.TEXT_HTML)
public Response checkLogin(#FormParam(Login.fieldUsername) String user, #FormParam(Login.fieldPsw) String psw) throws URISyntaxException {
boolean val = db.checkLogin(user, psw);
NewCookie cookie;
NewCookie cookie2;
if(val){
//Valid access + cookie creation
cookie = new NewCookie("username", user);
cookie2 = new NewCookie("hashedPassword", psw);
return Response.temporaryRedirect(new URI("/home")).cookie(cookie, cookie2).build();
} else {
//Wrong login + cookie deletion
cookie = new NewCookie("username", "");
cookie2 = new NewCookie("hashedPassword", "");
return Response.temporaryRedirect(new URI("/login")).cookie(cookie, cookie2).build();
}
}
login page
#GET
#Produces(MediaType.TEXT_HTML)
public Response showLoginForm() throws URISyntaxException{
boolean validCookie = db.checkLogin(username, hashedPassword);
String data = "<form name='Username' action='"+ redirect +"' method='post'><ul>"
+ "<li><label for='"+fieldUsername+"'>Username</label>"
+ " <input type='text' name='"+fieldUsername+"' placeholder='Insert username' required></li>"
+ "<li><label for='"+fieldPsw+"'>Password</label>"
+ " <input type='password' name='"+fieldPsw+"' placeholder='Insert password' required></li>"
+ "<li><input type='submit' value='Login'>"
+ "</li></ul></form>";
if(validCookie){
return Response.temporaryRedirect(new URI(homepage)).build();
}
else {
return Response.ok( showTheForm(data) ).build();
}
}
You can use:
Response.seeOther(redirecttUri).build();

Google Analytics OAuth2: How to solve error: "redirect_uri_mismatch"?

I'm trying to get this example to work: https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php#enable
The error I'm getting is "Error: redirect_uri_mismatch" .
In order to install the google api resources, I used composer with this command:
php composer.phar require google/apiclient:^2.0.0#RC
This installed the "vendor" folder in my root site folder. My index.php and oauth2callback.php files are located in the "public_html" folder.
Here's a screenshot of my error when going to my site:
The weird thing is that if I navigate to the link above that's included in the error message "Visit ...... to update the authorized..", I get this error message: " The OAuth Client Does Not Exist "
If I click on my only available Client ID, I can navigate to see the URI's which I'll screenshot below as well:
As you can see, under Authorized Javascript origins, I have http://localhost listed, and under authorized redirect URIs, I have my live site followed by the "oauthc2callback.php" file extension.
I don't understand how to get rid of the error I'm getting. I've tried replacing the URI's and putting in different JavaScript origins.
Also, for some reason on that last screenshot, it says that I don't have permission to edit this OAuth client, but I can make edits.
The code I have for index.php:
<?php
// Load the Google API PHP Client Library.
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
$results = getResults($analytics, $profile);
printResults($results);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getFirstprofileId(&$analytics) {
// Get the user's first view (profile) ID.
// Get the list of accounts for the authorized user.
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
// Get the list of properties for the authorized user.
$properties = $analytics->management_webproperties
->listManagementWebproperties($firstAccountId);
if (count($properties->getItems()) > 0) {
$items = $properties->getItems();
$firstPropertyId = $items[0]->getId();
// Get the list of views (profiles) for the authorized user.
$profiles = $analytics->management_profiles
->listManagementProfiles($firstAccountId, $firstPropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
// Return the first view (profile) ID.
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No properties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
function printResults(&$results) {
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "<p>First view (profile) found: $profileName</p>";
print "<p>Total sessions: $sessions</p>";
} else {
print "<p>No results found.</p>";
}
}
The code I have for "oauth2callback.php":
<?php
require_once '../vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfigFile('../config/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
All of this code was taken from the first website example, except with a few minor additions to make it match my system.
Anyone know how I can get rid of this error? What am I doing wrong?
Remember, as far as Google is concerned, "your" server is hostile until you name it "friendly", you must explicitly whitelist every possible source of an OAuth call TO Google.
Google is a clubbouncer, a big, ugly, unmovable bouncer with a a guest list saying to your application: "I will only deal with your request if your exact name OR id is on the list"
Have you tried including, not only localhost, but all other possible origins?
You must list every possible variation of url "root", including explicit IPs.
http://www.example.com
http://example.com
https://example.com
https://www.example.com
http://222.111.0.111
...
dont forget to include
https://accounts.google.com:443
The redirect Uri in the request MUST be exactly the same as one Uri you stored.
I see a / at the end of the stored one you missed in your request.
just copy the request URI on which error is occurring from error screen and paste it to OAuth credentials "Authorised redirect URIs"
now run the app.
this works for me. Hope I answered your query.

facebook.login() is not working in Corona SDK

I have went threw all the steps, creating a key hash for android for my game build in corona. I have create a Button for user login Facebook account. But don't have any error message and response when user touch the Button. Only have print output.
What am I missing? Please help.
I have create the Key Hashes using OPENSSL
Enter App ID from Facebook Developers
Enter Key Hashes to Facebook Developers
Enable "Single Sign On" and "Deep Linking"
Enter Class Name "com.ansca.corona.CoronaActivity" on Facebook Developers
include "android.permission.INTERNET" in build.settings
local facebook = require ("facebook")
local fbAppID = "49911xxxxxx"
local function onClick( event )
if ( "ended" == event.phase ) then
print( "Button was pressed and released" )
facebook.login( fbAppID, facebookListener, { "publish_actions, email" } )
end
end
-- Facebook Button
FacebookButton = widget.newButton
{
defaultFile = "images/fb.png" ,
width = 240,
height = 120,
onEvent = onClick,
}
FacebookButton.x = display.contentWidth / 2
FacebookButton.y = display.contentHeight / 2
I am unsure if you have fixed this problem but I too have been having problems with this. When you go to log in through Facebook and it gives you an error saying:
"invalid key hash code, it does not match xxxxxxxxxxxxx configure it in (your website here)" I copied the hash code and checked it over and over again...
Only to FINALLY realize that the lowercase "L" was actually an uppercase "i" o.0 it fixed it! Good luck to ya!
Also, here is a little code snippit that helped me a little
local function facebookListener(event)
if (event.type == "session") then
if (event.phase == "login") then
sessionToken = event.token
local response = event.response
native.showAlert("My Response", response)
--facebook.request("me", "GET", {fields = "email"})
elseif (event.type == "request") then
local response = event.response
native.showAlert("My Response", response)
end
end
end
facebook.login( appId, facebookListener, {"publish_actions, email, public_profile"})

How to get the access token automatically in facebook

I'm trying to make some sort of dashboard of my facebook in R. Some basic stuff. I would like to automate the script so that it can periodically update itself. I use knitr and task manager to produce the dashboard, which works well.
I use the facebook code of romainfrancois' blog to get the facebook data:
facebook <- function( path = "me", access_token = token, options){
if( !missing(options) ){
options <- sprintf( "?%s", paste( names(options), "=", unlist(options), collapse = "&", sep = "" ) )
} else {
options <- ""
}
url <- sprintf( "https://graph.facebook.com/%s%s&access_token=%s", path, options, access_token )
# print(url)
data <- getURL( url )
fromJSON( data )
}
The only problem is to get the access token automatically.
I tried to webscrape the token of the webpage:
library(RCurl)
FBdevPage<-browseURL("http://developers.facebook.com/tools/explorer")
FBdevPage[21]
It should be on line 21, according to the source code of the page. However, in R it only shows a backslash. Does someone had any ideas to get the access token? Or otherwise, store the procedure, while it allows to retrieve the data each time?

Login repeats after authenticate, if i try to send a friends request

Im trying to build a 'cheer action' for my app. It is a game in iPhone, so I want to post a 'welcome message' in the users wall (I will need 'public_stream' permission) and then invite his friends to visit my webpage.
Here my question.. I authenticate the user using:
_url = "http://www.facebook.com/dialog/oauth/?client_id=" + app_id + "&redirect_uri=" + app_net_folder + auth_response_uri + "&state=" + session_id;
I get response in my uri, and then I get the access_token, user_id, etc.
Then I post a message in his wall in this way:
_url = "https://www.facebook.com/dialog/apprequests?app_id=" + app_id;
_url += "&message=" + string_ToUrl(String_ToHTML(request_msg));
Now I want to invite his friends (using a multi friend list dialog). To do it, I can only use JavaScript FB.ui. In this way:
FB.init({appId : app_id, logging : false, frictionlessRequests: true, oauth : true});
FB.ui({method: 'apprequests', message: msg, title: title}, requestCallback);
When I do it, a window is opened asking me again for the user's login.. but my user has been already authenthicated. So I dont know how to say to FB in JavaScript that my user has been alredy authenthicated! (I even have the access_token, but I don't know how to use it in JavaScript functions).
Someone knows what am I doing wrong? or how to do those two actions asking just one time for the user's login?
Thanks!!
if you are already log in, you can get login user id using below code
var userId = FB.Facebook.apiClient.get_session().uid;
if(userId > 0 || userId != '')
{
alert('user is already log in');
}
hope it's helpful to you