Show login Page when user is not Authenticated - asp.net-mvc-4

I want to authorized the request in my project and I have an issue with popuppage.On button click I have open bootstrap dialog using below code.
$('#divModalActionPage .modal-body').load(strUrl, function(e){
var html=$("#divModalActionPage .modal-body").html();
var IsvalidJSON=IsJsonString(html);
$('#divModalActionPage').modal({
backdrop: 'static',
//keyboard: false,
show: true
})
}
And strUrl action decorate with [CustomAuthorize] attribute and my CustomAuthorize contains following code.
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result=new ContentResult() { Content = "<script>top.window.location.href='/Home/Index'</script>" };
}
}
The issue is that when I click on the button it will go to check use is authenticated or not but not redirect me to the login page.

Related

I am trying to login to the application but it says "A native alert dialog was invoked on page", I tried manually and could not see any dialog box

I am new to test cafe. I am trying to login to the application but it says " A native alert dialog was invoked on page, but no handler was set for it. Use the "setNativeDialogHandler" function to introduce a handler function for native dialogs.", I tried manually and could not see any dialog box.
page and function to login
import { Selector } from 'testcafe';
class Page {
constructor () {
this.loginInput = Selector("input[name*='username']");
this.passwordInput = Selector("input[name*='password']");
this.submitButton = Selector("div[role=button] div[class='gw-label']");
}
async login (t) {
await t
.maximizeWindow()
.typeText(this.loginInput, 'testRole')
.typeText(this.passwordInput, 'P#ssw0rd')
.setNativeDialogHandler(() => true)
.click(this.submitButton);
await t.wait(2000)
.expect(Selector("div[class = 'gw-TitleBar--title']").innerText).contains('Dashboard');
}
}
export default new Page();
Test:
website backend code:
enter code here

Remote model annotation refreshes page on success

Model Class
[Remote(
"isExaminationTemplateInUse",
"GENExaminationTemplate",
AdditionalFields = "ExaminationTemplateID",
ErrorMessage = "Template Name already exists.",
HttpMethod = "POST"
)]
[Required(ErrorMessage = "Template Name is required.")]
[DisplayName("Name")]
public String ExaminationTemplateName { get; set; }
Controller
[HttpGet]
[HttpPost]
[Route("isExaminationTemplateInUse")]
public async Task<ActionResult> isExaminationTemplateInUse(String ExaminationTemplateName, int ExaminationTemplateID)
{
return Json(true);
}
AJAX Part
//Submit Main Form.
$(document.body).on("submit", "#mainForm", function (event) {
//Prevent Default Region.
event.preventDefault();
//Post Region.
//Serialize the form datas.
$.ajax({
url: '/GENExaminationTemplate/SetExaminationTemplate',
type: "post",
async: true,
data: { pstrJSONMasterData: jsonMasterData },
success: function (response) {
window.location.href = response;
}
});
});
Add New Record Mode, Works Fine. Reason: In this mode focus moves through the field and on submit it does not go for validation.
Edit Record Mode, Not Works Fine. Reason: Focus not moves through the field, On click of submit button system moves into action "isExaminationTemplateInUse" and on line "return Json(true);" refreshes page, that moves to page load function rather page save function. However, by just passing focus through the field that is using [Remote], system works fine.
In scripts section following file references are also present on top of the page.
jquery.js,jquery.validate.js, jquery.validate.unobtrusive.js

Authenticate with Moodle from a mobile app

My mobile app needs to log in to Moodle to get Json data from a webservice and display it using Angular.
In order to do that, I need to pass in a username and password and get a Moodle webservice token back, so my app doesn't need to log in again (at least until the token expires).
(this is one of those "ask and answer your own question" things, so my solution is below, but comments & suggestions welcome.)
With thanks to all the other StackOverflow pages I have used to create this solution!
See also - how to get data from your Moodle webservice with Angular.
Step 1. Check if a token already exists
jQuery(document).ready(function () {
/* when the user clicks log-out button, destroy the session */
$('#btn_logout').on('click', function () {
$('.pane').hide(); /* hide all screens */
$('#menu').toggleClass('ui-panel-open ui-panel-closed');
$.jStorage.deleteKey('session');
makeUserLogin();
});
var session = $.jStorage.get('session', ''); // syntax: $.jStorage.get(keyname, "default value")
if (session) { // if there is already a session, redirect to landing pane
showApp();
} else { // if there is no session *then* redirect to the login pane
makeUserLogin();
}
});
Step 2. create functions to show app & redirect to login page
function showApp() {
$('#home-pane').show(); /* show home screen */
$('#system-message').hide();
$('#login-pane').hide(); /* hide login screen*/
$('#menu_btn').removeClass('hidden'); /* show menu button so user can see rest of app */
}
function makeUserLogin() {
$('#btn_login').click(function () {
console.log('click event for login_button');
var username = $('#username').val();
var password = $('#password').val();
postCredentials(username, password, createSession);
});
$('#menu_btn').addClass('hidden'); /* hide menu button so user cannot see rest of app */
$('#home-pane').hide(); /* hide home screen */
$('#login-pane').show(); /* show login screen */
}
function postCredentials(username, password, callback) {
if ((username.length && password.length) && (username !== '' && password !='')) {
var url = 'https://moodle.yourcompany.com/local/login/token.php';
$.post(url, {
username: username,
password: password,
service: 'webservice_ws' // your webservice name
}).done(function (data) {
token = data.token;
dataString = JSON.stringify(data);
if (dataString.indexOf('error') > 0) {
showErrorDialog('<p class="error">Invalid user credentials, please try again</p>');
}
else {
createSession(token);
}
}).fail(function () {
showErrorDialog('<p class="error">Login failed</p>');
});
} else {
showErrorDialog('<p class="error">Please enter a username and password</p>');
}
}
function createSession(token) {
// syntax: $.jStorage.set('keyname', 'keyvalue', {TTL: milliseconds}); // {TTL... is optional time, in milliseconds, until key/value pair expires}
$.jStorage.set('session', token, { TTL: 28800000 });
// redirect to whatever page you need after a successful login
showApp();
}
function showErrorDialog(errorMsg) {
$('#system-message').html(errorMsg);
$('#system-message').fadeIn();
}

Pass data to component after it has finished routing

I have a navbar-login (login form in navbar) and a page-login (a page with login-form which can be routed to). The navbar-login-form and the page-login-form are two-way-binded via a service (see first codebit below).
What I want is the following flow:
User enters email and password in navbar-login
On Clicking Submit Button, the credentials are sent to a login.service
If credentials are wrong, the service routes to the login-page with the credentials displayed
The two-way-binding with the service works fine if the page-login is already displayed. But if it wasn't displayed and I enter credentials and hit the button, it only routes to page-login but does not pass the credentials.
I'm using the following service to have navbar-login and page-login communicate with each other (two-way-binding across "unrelated" components):
export class LoginNav2PageService {
viewerChange: EventEmitter<{email:string,password:string}> = new EventEmitter();
constructor() {}
emitNavChangeEvent(user:{email:string,password:string}) {
this.viewerChange.emit(user);
}
getNavChangeEmitter() {
return this.viewerChange;
}
}
This is the navbar component, pass2page is hooked with a keyup event in the HTML inputs:
export class LoginNavbarComponent {
user:= {email:'',password:''};
constructor(private _loginNav2pageService:LoginNav2PageService, private _loginService:LoginService){}
pass2page(){
this._loginNav2pageService.emitNavChangeEvent(this.user);
}
onNavbarLoginBtn(){
this._loginService.onNavbarLogin(this.user);
}
}
And this is the listener in the page-login component:
export class LoginPageComponent implements OnInit{
user= {email:"", password:""};
subscription:any;
constructor(private _loginNav2pageService:LoginNav2PageService){}
ngOnInit():any{
this.subscription = this._loginNav2pageService.getNavChangeEmitter().subscribe(user => this.setViewer(user));
}
setViewer(user:{email:string, password:string}){
this.user = user;
}
}
And finally the loginService:
export class LoginService{
constructor(private _router:Router, private _loginNav2pageService:LoginNav2PageService){}
//login User from Navbar
onNavbarLogin(user:LoginUserInterface){
//login and routing if successful
if(user.email === 'name' && user.password === '1234'){
console.log("Login Success");
//route to platform
}
//else route to login page to show validation errors to users
else {
this._router.navigate(['Login']);
this._loginNav2pageService.emitNavChangeEvent(user);
console.log("wrong credentials");
}
}
}
after a good nights sleep I figured it out :), the code above was a snippet i adapted before in some other parts and way to complicated for this....
Now i'm simply using the ngAfterViewInit Lifecycle Hook to get the data from the service.
Thanks!

Programmatically closing a Durandal modal

I'm new to Durandal, so I might be taking the wrong approach to my problem.
I want to show a modal popup with a message of 'logging in...please wait' when the user has clicked the login button. I want to close the modal popup once the response is received. My attempted approach is to call a custom modal popup using Durandal's app.showModal and a view with no buttons, from the login view model. This shows the modal popup I'm after, but I haven't been able to figure out how to close the popup once the server response is received. All the examples I've seen have a button on the modal popup view that closes the popup.
Is this possible? If not, is there a better approach that will show the user something is happening and also stop the user from trying to use any other button on the view?
Here's the view model code for the login view (with extraneous code removed):
define(['services/appsecurity', 'durandal/plugins/router', 'services/utils', 'services/errorhandler', 'durandal/app', 'viewmodels/controls/activityindicator'],
function (appsecurity, router, utils, errorhandler, app, activityIndicator) {
var username = ko.observable().extend({ required: true }),
password = ko.observable().extend({ required: true, minLength: 6 }),
rememberMe = ko.observable(),
returnUrl = ko.observable(),
isRedirect = ko.observable(false),
var viewmodel = {
username: username,
password: password,
rememberMe: rememberMe,
returnUrl: returnUrl,
isRedirect: isRedirect,
appsecurity: appsecurity,
login: function() {
var credential = new appsecurity.credential(this.username(), this.password(), this.rememberMe() || false),
self = this;
activityIndicator.message = 'Logging in...please wait';
app.showModal(activityIndicator);
appsecurity.login(credential, self.returnUrl())
.fail(self.handlevalidationerrors)
.always(function() { activityIndicator.close(); });
}};
return viewmodel;
});
The appsecurity.login function is the ajax post call. The view model for the custom modal is:
define(function () {
var activityIndicator = function (message, title, options) {
this.message = message;
this.title = title || activityIndicator.defaultTitle;
this.options = options || activityIndicator.defaultOptions;
this.close = function() {
this.modal.close();
};
};
return activityIndicator;
});
When running this, I get an error on .always(function() { activityIndicator.close(); }); of close is undefined.
Note for anyone using Durandal 2.0, the above marked answer only works in earlier 1.x versions. Happy coding!
Found the problem. The viewmodel for the custom modal was wrong, so the close() method was undefined. The working viewmodel is:
define(function () {
var message = ko.observable();
var activityIndicator = {
message: message,
close: function() {
this.modal.close();
}
};
return activityIndicator;
});