You are on page 1of 8

[HttpPost]

[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string
button)
{
// check if we are in the context of an authorization request
var context = await
_interaction.GetAuthorizationContextAsync(model.ReturnUrl);

// the user clicked the "cancel" button


if (button != "login")
{
if (context != null)
{
// if the user cancels, send a result back into IdentityServer
as if they
// denied the consent (even if this client does not require
consent).
// this will send back an access denied OIDC error response to
the client.
await _interaction.DenyAuthorizationAsync(context,
AuthorizationError.AccessDenied);

// we can trust model.ReturnUrl since


GetAuthorizationContextAsync returned non-null
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}

return Redirect(model.ReturnUrl);
}
else
{
// since we don't have a valid context, then we just go back to
the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
PrincipalContext principalContext = new
PrincipalContext(ContextType.Domain);
bool isAuthenticated = false;
UserPrincipal userPrincipal = null;
UserFactory userFactory = null;
userFactory = _applicationDb.UserFactories.Where(factory =>
factory.Id == model.FactoryId).FirstOrDefault();
try
{
isAuthenticated =
principalContext.ValidateCredentials(model.Username, model.Password,
ContextOptions.Negotiate);

if (isAuthenticated)
{
userPrincipal =
UserPrincipal.FindByIdentity(principalContext, model.Username);
}
}
catch (Exception)

{
isAuthenticated = false;
userPrincipal = null;
}

if (!isAuthenticated)
{
if (!isAuthenticated || userPrincipal == null)
{
// ModelState.AddModelError(string.Empty, "Username or
Password is not correct.");
// return AuthenticationResult.FAILED("Username or Password
is not correct.");
var resul = await
_userManager.FindByNameAsync(model.Username);
if (resul != null)
{
#region UserRoele // when fist login in another app
await CheckIdentityAuthenAsync(resul, userFactory);
var checkuser = await
_userManager.FindByNameAsync(model.Username);
if (checkuser != null && context != null)
{

var userAuthorities =
_applicationDb.UserAuthoritys.Where(userauthor => userauthor.UserApplication.Name
== context.Client.ClientId.ToString()

&& userauthor.ApplicationUser.UserName == model.Username

&& userauthor.UserFactory == userFactory

).FirstOrDefault();
if (userAuthorities == null)
{
var user = await
_userManager.FindByNameAsync(model.Username);
var UserAuthen = await
DefaultUserAuthenAsync(context, user, userFactory);
}
}

#endregion

var signIn_normaluser = await


_signInManager.PasswordSignInAsync(model.Username, model.Password,
model.RememberLogin, lockoutOnFailure: true);
if (signIn_normaluser.Succeeded)
{
var user = await
_userManager.FindByNameAsync(model.Username);
if (model.FactoryId != user.CurrentFactoryId)
{
user.CurrentFactoryId = model.FactoryId;
await _userManager.UpdateAsync(user);
}
await _events.RaiseAsync(new
UserLoginSuccessEvent(model.Username, user.Id, model.Username, clientId:
context?.Client.ClientId));
}

if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how
to
// return the response is for better UX for the
end user.
return this.LoadingPage("Redirect",
model.ReturnUrl);
}
//
ClaimsPrincipal.Current.Identities.First().Claims.ToList();

// we can trust model.ReturnUrl since


GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}

// request for a local page


if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link -
should be logged
throw new Exception("invalid return URL");
}

ModelState.AddModelError(string.Empty, "Username or
Password is not correct.");
// can't find user name or wrong password
var vmw = await BuildLoginViewModelAsync(model);
return View(vmw);

}
if (userPrincipal.IsAccountLockedOut())
{
ModelState.AddModelError(string.Empty, "Your account is
locked.");
// something went wrong, show form with error
var vmw = await BuildLoginViewModelAsync(model);
return View(vmw);
}
if (userPrincipal.Enabled.HasValue &&
userPrincipal.Enabled.Value == false)
{
ModelState.AddModelError(string.Empty, "Your account is
disabled.");
// return AuthenticationResult.FAILED("Your account is
disabled.");
// something went wrong, show form with error
var vmw = await BuildLoginViewModelAsync(model);
return View(vmw);
}
if (model.WindowAuthen)
{
ModelState.AddModelError(string.Empty, "Username or
Password is not correct.");
// can't find user name or wrong password
var vmw = await BuildLoginViewModelAsync(model);
return View(vmw);
}
}

Microsoft.AspNetCore.Identity.SignInResult result;
if (isAuthenticated)
{

var user = _userManager.FindByNameAsync(model.Username).Result;


var email =
_userManager.FindByEmailAsync(userPrincipal.EmailAddress).Result;
//1 st login
if ((user == null) && (email == null))
{

user = new ApplicationUser


{
Id = userPrincipal.Guid.ToString(),

UserName = userPrincipal.Name,
Email = userPrincipal.EmailAddress,
PhoneNumber = userPrincipal.VoiceTelephoneNumber,
PhoneNumberConfirmed = true,
EmailConfirmed = true,
CurrentFactoryId = userFactory.Id,
WindowAuthen = true,
};

var createuser = _userManager.CreateAsync(user).Result;


if (createuser.Succeeded)
{

var signIn = await


_signInManager.PasswordSignInAsync(model.Username, model.Password,
model.RememberLogin, lockoutOnFailure: true);
if (signIn.Succeeded != true)
{
var reset_token =
_userManager.GeneratePasswordResetTokenAsync(user);
var newpassword = await
_userManager.ResetPasswordAsync(user, reset_token.Result, model.Password);
signIn = await
_signInManager.PasswordSignInAsync(model.Username, model.Password,
model.RememberLogin, lockoutOnFailure: true);
}
await CheckIdentityAuthenAsync(user, userFactory);
#region UserRoele

var UserAuthen = await DefaultUserAuthenAsync(context,


user, userFactory);

#endregion
await _events.RaiseAsync(new
UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId:
context?.Client.ClientId));

if (string.IsNullOrEmpty(model.ReturnUrl))
{
// build a model so we know what to show on the
login page
return Redirect("~/");
}
// we can trust model.ReturnUrl since
GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
else
{
await _events.RaiseAsync(new
UserLoginFailureEvent(model.Username, "Can't create user from this site", clientId:
context?.Client.ClientId));
ModelState.AddModelError(string.Empty, "Can't create
user from this site please login from TTDD Application if you have any question
please contact Admin ");
// something went wrong, show form with error
var vmL = await BuildLoginViewModelAsync(model);
return View(vmL);
}
}

result = await
_signInManager.PasswordSignInAsync(model.Username, model.Password,
model.RememberLogin, lockoutOnFailure: true);
if (result.Succeeded != true)
{
var reset_token =
_userManager.GeneratePasswordResetTokenAsync(user);
var newpassword = await
_userManager.ResetPasswordAsync(user, reset_token.Result, model.Password);
result = await
_signInManager.PasswordSignInAsync(model.Username, model.Password,
model.RememberLogin, lockoutOnFailure: true);
}
//var user = await
_userManager.FindByNameAsync(model.Username);
if (model.FactoryId != user.CurrentFactoryId)
{
user.CurrentFactoryId = model.FactoryId;
await _userManager.UpdateAsync(user);
}
#region UserRoele
if (result.Succeeded == true)
{
await CheckIdentityAuthenAsync(user, userFactory);
if (context != null)
{
var userAuthorities =
_applicationDb.UserAuthoritys.Where(userauthor => userauthor.UserApplication.Name
== context.Client.ClientId.ToString()

&& userauthor.ApplicationUser.UserName == model.Username

&& userauthor.UserFactory == userFactory

).FirstOrDefault();
if (userAuthorities == null)
{

var UserAuthen = await


DefaultUserAuthenAsync(context, user, userFactory);

}
}
}
#endregion //not fist login

await _events.RaiseAsync(new
UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId:
context?.Client.ClientId));

if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end
user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
//
ClaimsPrincipal.Current.Identities.First().Claims.ToList();

// we can trust model.ReturnUrl since


GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}

// request for a local page


if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link - should be
logged
throw new Exception("invalid return URL");
}
}

await _events.RaiseAsync(new UserLoginFailureEvent(model.Username,


"invalid credentials", clientId: context?.Client.ClientId));
ModelState.AddModelError(string.Empty,
AccountOptions.InvalidCredentialsErrorMessage);
}

// something went wrong, show form with error


var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
private async Task<bool> CheckIdentityAuthenAsync(ApplicationUser user,
UserFactory CurrentFactory)
{

int countroleidentityserver =
_applicationDb.UserAuthoritys.Where(Author => Author.ApplicationUser == user &&

Author.UserApplication.Name == "Identityserver" &&

Author.UserFactory == CurrentFactory).Count();

int countroleidentityManagment =
_applicationDb.UserAuthoritys.Where(Author => Author.ApplicationUser == user &&

Author.UserApplication.Name == "ICLMS.IdentityManagement" &&

Author.UserFactory == CurrentFactory).Count();

if (!(countroleidentityserver > 0))


{
var role = await _roleManager.FindByNameAsync("Guest");
var appname = _applicationDb.UserApplications.FirstOrDefault(x =>
x.Name == "Identityserver");
var userauthority = new UserAuthority
{
ApplicationUser = user,
UserFactory = CurrentFactory,
UserRole = role,
UserApplication = appname
};
_applicationDb.UserAuthoritys.Add(userauthority);
_applicationDb.SaveChanges();
}
if (!(countroleidentityManagment > 0))
{
var role = await _roleManager.FindByNameAsync("Guest");
var appname = _applicationDb.UserApplications.FirstOrDefault(x =>
x.Name == "ICLMS.IdentityManagement");
var userauthority = new UserAuthority
{
ApplicationUser = user,
UserFactory = CurrentFactory,
UserRole = role,
UserApplication = appname
};
_applicationDb.UserAuthoritys.Add(userauthority);
_applicationDb.SaveChanges();
}

return true;
}

You might also like