ember-simple-auth cookieExpirationTime not working - ruby-on-rails

I need to implement a "remember me" feature in my application.
I am using the built-in devise authenticator and have the following as my Session Store:
// app/session-stores/application.js
import CookieStore from 'ember-simple-auth/session-stores/cookie';
export default CookieStore.extend({
cookieName: 'myapp-session-cookie'
});
I have a login-form component with the following:
rememberMe: false,
setExpirationTime() {
const expirationTime = this.get('rememberMe') ? (14 * 24 * 60 * 60) : null;
this.set('session.store.cookieExpirationTime', expirationTime);
},
actions: {
authenticateWithDevise() {
this.setExpirationTime();
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:devise', identification, password).then(() => {
this.sendAction('onLoggedIn');
}).catch((reason) => {
this.set('errorMessage', reason.errors[0]);
});
}
}
and of course in the corresponding template I have:
<form role="form" {{action "authenticateWithDevise" on="submit"}}>
{{input type="email" value=identification placeholder="Email" class="icon-email"}}
{{input type="password" value=password placeholder="Password" class="icon-lock"}}
{{input id='remember_me' type='checkbox' checked=rememberMe}}
</form>
What happens is session is never remembered, no matter whether cookieExpirationTime was set or null.
My question is: should I also implement something else on the server side? I'm currently using devise's rememberable. Also, I've tried searching both here and on github but can only find conversations and code that seems obsolete, like this:
https://github.com/simplabs/ember-simple-auth/pull/451
Can somebody please shed some light? Thanks!

Related

Issue in react final form

I am using react final form for validation purpose for login page which has forgot password and register link as well, now when I am clicking forgot password or register link ,it should not trigger any validation even though I am not filling my user name and password .I have tried t keep forgot password and register link away from tag but it is still triggering the validation on click of forgot password and register link .It should only trigger the validation when I m hitting submit button.
It should not ask to validate the form when I am clicking on any hyper link on the page as hyperlinks does not have any validations.
Here is the code sample
loginPage = () => {
const {t: translate} = this.props;
const {
match: {
params: {
authUrlKey = ''
} = {},
} = {},
} = this.props;
return (
<Form
onSubmit={ (values)=> this.validateUserCredentials(values)}
render={({ handleSubmit}) => (
<form onSubmit={handleSubmit}>
<button className="hidden" type="submit"/>
<h1 className="hw-block--pb">{translate('login.heading')}</h1>
<p className="hw-text-lead hw-block--pb-small">{translate('login.text')}</p>
{ this.state.description !=='' && <p className="hw-text-lead hw-block--pb-small">{this.state.description}</p> }
<div className="hw-grid">
<div className="hw-grid__item hw-one-whole hw-medium--one-fifth hw-large--one-sixth">
<label className="hw-label">{translate('login.landcode')}
<Field name="landcode" component={Dropdown} options={getCountryList()} onOptionSelect={this.onCountrySelect}/>
</label>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--four-fifths hw-large--five-sixths">
<label className="hw-label">{translate('login.mobileNumber')}
<Field type="text" component={InputType}
validate={composeValidators(mobileNumberRequired, validMobileNumberWithISDCode)}
placeholder={translate('login.mobileNumberPlaceHolder')} name="phoneNumber"/>
</label>
</div>
</div>
<label className="hw-label">{translate('login.password')}
<Field type="password" component={InputType} validate={passwordRequired} placeholder={translate('login.passwordPlaceHolder')} name="password"/>
</label>
<Link className="hw-link" to={{ pathname: '/password/reset', state: {authUrlKey} }}>{translate('login.forgotPassword')}</Link>
<ErrorInfo error={this.state.error} errorMessage={this.state.errorMessage} translate={translate}/>
<div className="hw-block hw-block--mt-small">
<div className="hw-grid">
<div className="hw-grid__item hw-small--one-whole hw-medium--one-quarter hw-block--mb-smaller">
<button className="hw-button hw-button--primary hw-button--full" type="submit">{translate('login.loginButton')}</button>
</div>
<div className="hw-grid__item hw-one-whole hw-medium--three-quarters hw-block--mt-smaller">
<Link className="hw-link"
to={{ pathname: '/register', state: {authUrlKey} }}>{translate('login.registerButton')}</Link>
</div>
</div>
</div>
</form>)}
/>
)}
validations function used in code
export const validMobileNumberWithISDCode = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\+?((45)|(46)|(47))?( )?\d{8,10}$/
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const validMobileNumber = (fieldValue='') => {
const value = trimValue(fieldValue);
const regex1 = /^\d{8,10}$/;
return (regex1.test(value))? undefined : message[root.lang].validMobileNumber;
}
export const mobileNumberRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].mobileNumberRequired;
}
export const passwordRequired = (fieldValue='') => {
const value = trimValue(fieldValue);
return value ? undefined: message[root.lang].passwordRequired;
}
export const required =(fieldValue)=> {
const value = trimValue(fieldValue);
return value ? undefined : message[root.lang].required;
}```
validateUserCredentials -> This function does not contains any validation.It is used to retrieve form values and send it to server
React Final Form calls your validation function on every value change in the form, to ensure that the form validity is always up to date. Since you did not include the code for your validation function, I cannot ascertain what you are attempting to do. Your validation function should be very cheap to run (e.g. required fields, value length, etc.). The actual authentication should happen on submit.

Session and cookie value using Cross Domain in .net

I have two projects - an MVC project and the other an API project. I have placed the login form and script in the MVC project and the back end is in the API project.
I have written the login form as below:
<form>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control" id="pwd" placeholder="Password">
</div>
<button id="buttonSubmit" class="btn btn-default">LOG IN</button>
</form>
The script for login submit when a customer has filled in the above form:
var user =
{
UserName: $("#email").val(),
Password: $("#pwd").val(),
IsRemember: $(".customCheckBox").val()
}
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/loginmethod",
data: user,
success: function (response) {
document.cookie = "UserName = " + response.UserName;
}
});
Then I have created session using API project as below:
[HttpPost]
[Route("api/ajaxapi/loginmethod")]
public UserValuesForLogOn AjaxLogOnMethod(UserValuesForLogOn user)
{
HttpContext.Current.Session["authToken"] = user;
return user;
}
After logged in I have called ajax post to get details as below, which is in the MVC project:
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/caselistmethod",
success: function (response) {
}
});
Then I have written code in the API project to take session value as stored while login process:
[HttpPost]
[Route("api/ajaxapi/caselistmethod")]
public List<UserValuesForLogOn> AjaxCaseListMethod()
{
userDetails = (UserValuesForLogOn)HttpContext.Current.Session["authToken"];
return userDetails;
}
Both cookie and session values can't take in API project. Please help me. Is it possible to access session and cookie in a cross domain situation.
Thanks.

MVC 5 - Prevent password storing

I need to prevent the storing of username/password on my MVC 5 site.
I have set the both the form and input elements to autocomplete="off" and I'm sure the site is running HTML5. For all intents and purposes it should not want to store the login information, yet, it still prompts for it after login.
As suggested, I tried changing the input field names to something other than "username" and "password", but it changed nothing.
I have even tried the trick of adding dummy username & password hidden elements outside the form, tried inside the form as well. No joy.
I have also tried doing it in jQuery, with no success
$("input").attr("autocomplete", "off");
Form tag:
<form action="/" autocomplete="off" class="form-horizontal" method="post" role="form" novalidate="novalidate">
input element:
<input autocomplete="off" class="form-control" data-val="true" data-val-regex="Mobile number must be a Numbers only." data-val-regex-pattern="[0-9]*\.?[0-9]+" data-val-required="The Mobile field is required." id="Username" name="Username" type="text" value="">
Tested in IE and chrome, but prompt to save info.
Any help or advice would be greatly appreciated. How do banks prevent this?
I tested many solution and finally, came with this one.
HTML code
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #placeholder = "UserName", #autofocus = "", #autocomplete = "off" })
#Html.TextBoxFor(m => m.Password, new { #class = "form-control", #placeholder = "Password", #autocomplete = "off" })
CSS code
#Password {
text-security: disc;
-webkit-text-security: disc;
-moz-text-security: disc;
}
JavaScript code
window.onload = function () {
init();
}
function init() {
var x = document.getElementsByTagName("input")["Password"];
var style = window.getComputedStyle(x);
console.log(style);
if (style.webkitTextSecurity) {
// Do nothing
} else {
x.setAttribute("type", "password");
}
}

angularJS with MVC call - how to do something other than CRUD?

I've been following web tutorials to try to learn angularJS on a .NET MVC Application. All the tutorials seem to cover getting a list, getting an individual item etc.
What I want to do is allow the user to fill in an email address, I want to verify that email address against the database and return true or false if it existed. I'm then trying to put that value in the scope so I can do something in response to whether its true or false.
I'm using a single page app so this is the login html.
<form name="form" class="form-horizontal">
<div class="control-group" ng-class="{error: form.ValidEmailAddress.$invalid}">
<label class="control-label" for="ValidEmailAddress">Valid Email Address</label>
<div class="controls">
<input type="email" ng-model="item.ValidEmailAddress" id="ValidEmailAddress">
</div>
</div>
<div class="form-actions">
<button ng-click="login()" class="btn btn-primary">
Go!
</button>
<label ng-if="user.isAuthorised">Authorised</label>
<label ng-if="!user.isAuthorised">NotAuthorised</label>
</div>
</form>
In my app.js file I declare a loginCtrl controller when the url was /login so that's all fine. The logic that I'm calling on my button click is this:
var LoginCtrl = function ($scope, $location, $http, AuthorisedUser) {
$scope.login = function() {
var isValidUser = $http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress);
$scope.user.isAuthorised = isValidUser;
} };
Which is then calling an MVC AuthorisedUserController class method:
public bool IsValidUser(string id)
{
var list = ((IObjectContextAdapter)db).ObjectContext.CreateObjectSet<ApprovedUser>();
var anyItems = list.Any(u => u.ValidEmailAddress == id);
return anyItems;
}
So it vaguely seemed to be working when I put in a value like "aaa" into the textbox. But as soon I try putting in an email address the value is undefined. Maybe I'm supposed to be doing a post but the only thing I can successfully hit my .NET controller with is by using get.
I'm sure I'm missing fundamental knowledge and potentially tackling this in the wrong way.
In case it helps I've created a module and defined factories like this:
var EventsCalendarApp = angular.module("EventsCalendarApp", ["ngRoute", "ngResource"]).
config(function ($routeProvider) {
$routeProvider.
when('/login', { controller: LoginCtrl, templateUrl: 'login.html', login: true }).
otherwise({ redirectTo: '/' });
});
EventsCalendarApp.factory('AuthorisedUser', function ($resource) {
return $resource('/api/AuthorisedUser/:id', { id: '#id' }, { isValidUser: { method: 'GET' } });
});
One of my questions is - should I be accessing the controller method using the $http object, or is there a way of using my factory declaration so that I can go something like:
AuthorisedUser.IsValidUser($scope.item.validEmailAddress)
I know in the tutorial I was following I could do stuff like:
CalendarEvent.save()
to be able to call a CalendarEventController post method.
What i think is, your get() function will return a promise. and you can't assign promise like this. so better try this approch once. I hope, it'd work. if not please let me know...
here I assume your first,second and third snippet of code works fine...
$http.get("/AuthorisedUser/IsValidUser/" + $scope.item.ValidEmailAddress).success(function (result, status) {
var isValidUser=result;
$scope.user.isAuthorised = isValidUser;
$scope.$apply();
}).error(function (result, status) {
//put some error msg
});

jQuery Mobile: Injected content appears then disappears immediately

I have a login page using jQuery Mobile which contains the following code:
<div id="loginPage" data-role="page" data-theme="a">
<div data-role="content">
<div id="alerts"></div>
<form id="login-form">
<input type="text" id="username" name="username" value="" placeholder="username or email" />
<input type="password" id="password" name="password" value="" placeholder="password" />
<button id="login-button" onClick="userLogin()">Login</button>
</form>
</div><!-- /content -->
</div><!-- /page -->
Here is a part of my javascript that is called when the user clicks the 'Login' button. If one of the fields is left blank, I see the following text injected into the #alerts div, but then within a fraction of a second the content has disappeared again.
if (username.length == 0 || password.length == 0) {
//alert('Please enter your username or email and your password');
$('#alerts').html('Please enter your username or email and your password.').trigger('create');
}
I also tried this using .append() instead of .html(). Same result with both. I've commented out my test alert(), which works when one of the fields is left blank.
What can I do to make sure the content remains on the page once it is injected?
Thank you for any help or insight you can offer! -Mark
Per Jasper's request, here is all of the javascript that is executed when the 'Login' button is clicked:
function userLogin() {
var username = $("#username").val();
var password = $("#password").val();
if (username.length == 0 || password.length == 0) {
$('#alerts').append('Please enter your username or email and your password.').trigger('create');
}
else {
$.post("services/user-status.php", { type: 'login', username: username, password: password },
function(data) {
var response = data.item;
console.log(response);
if (response.loggedIn == false) {
$('#alerts').html('The username/email and password you used did not work. Please try again.').trigger('create');
}
else {
localStorage.userID = response.userID;
localStorage.username = response.username;
localStorage.userStatus = 'loggedIn';
$.mobile.changePage('profile.html');
}
},'json');
}
}
It looks like you need to stop the propagation of the click event from firing for your button. You can do that by returning false in the click event handler:
HTML --
<button id="login-button" onClick="return userLogin()">Login</button>
JS --
function userLogin() {
...
return false;
}​
Here is a demo: http://jsfiddle.net/BkMEB/3/
Also, since you are using jQuery, you can bind to the <button> element like this:
$('#login-button').bind('click', userLogin);
This is the same as putting onClick="return userLogin()" as an attribute of the button but allows you to remove your inline JS.
Here is a demo: http://jsfiddle.net/BkMEB/4/

Resources