This repository has been archived on 2025-02-19. You can view files and clone it, but cannot push or open issues or pull requests.
Amen/Amen/Controllers/AccountController.cs
2022-09-20 08:40:13 -07:00

600 lines
23 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Amen.Models;
using Facebook;
using System.Data.Entity;
namespace Amen.Controllers
{
[Authorize]
public class AccountController : BaseController
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl, string affiliatekey)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, string affiliatekey)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
var user = controllerHelper.db.Users.Include("Affiliate").FirstOrDefault(i => i.Email == model.Email);
if (user != null)
{
user.LastLoginDateUtc = DateTime.UtcNow;
controllerHelper.db.SaveChanges();
affiliatekey = user.Affiliate.Key;
}
return RedirectToLocal(returnUrl, affiliatekey);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe, string affiliatekey)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model, string affiliatekey)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl, affiliatekey);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register(string affiliatekey)
{
var affiliate = new ControllerHelper().GetAffiliate(affiliatekey);
var model = new RegisterViewModel()
{
EnableSmsNotifications = true,
EnableEmailNotifications = true,
AffiliateEnableShowLocation = affiliate.EnableShowLocation,
AffiliateEnableShowName = affiliate.EnableShowName,
AffiliateIsSmsCapable = affiliate.IsSmsCapable
};
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, string affiliatekey)
{
if (ModelState.IsValid)
{
var affiliate = new ControllerHelper().GetAffiliate(affiliatekey);
var user = new ApplicationUser { FullName = model.FullName, UserName = model.Email, Email = model.Email, AffiliateId = affiliate.Id, LastLoginDateUtc = DateTime.UtcNow, EnableSmsNotifications = model.EnableSmsNotifications, EnableEmailNotifications = model.EnableEmailNotifications, Location = model.Location, ShouldShowLocation = model.ShouldShowLocation, ShouldShowName = model.ShouldShowName };
//return View(model);
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
//string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code, affiliatekey = affiliatekey }, protocol: Request.Url.Scheme);
//await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
//TODO: redirect to note indicating confirmation email was sent
return RedirectToAction("Index", "Prayer", new { affiliatekey = affiliatekey });
}
//AddErrors(result);
//hack to not show the "Name [emailaddress] is already taken." error
foreach (var error in result.Errors)
{
if (error.StartsWith("Name") && error.EndsWith("is already taken."))
continue;
ModelState.AddModelError("", error);
}
if (result.Errors.Count(i => i.StartsWith("Email") && i.EndsWith("is already taken.")) > 0)
ViewBag.ShowResetPassword = true;
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code, string affiliatekey)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword(string affiliatekey)
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model, string affiliatekey)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
//TODO: determine if we only send forgot password requests to confirmed users
if (user == null) // || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation(string affiliatekey)
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code, string affiliatekey)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model, string affiliatekey)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation(string affiliatekey)
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl, string affiliatekey)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl, affiliatekey = (ViewBag.AffiliateKey ?? ControllerHelper.DefaultAffiliateKey) }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe, string affiliatekey)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model, string affiliatekey)
{
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string affiliatekey)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// added the following lines
if (loginInfo.Login.LoginProvider == "Facebook")
{
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var access_token = identity.FindFirstValue("FacebookAccessToken");
var fb = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field
loginInfo.Email = myInfo.email;
loginInfo.DefaultUserName = identity.Name;
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
var user = controllerHelper.db.Users.Include("Affiliate").Where(i => i.Logins.Count(l => l.ProviderKey.Equals(loginInfo.Login.ProviderKey)) > 0).FirstOrDefault();
if (user != null)
{
user.LastLoginDateUtc = DateTime.UtcNow;
controllerHelper.db.SaveChanges();
affiliatekey = user.Affiliate.Key;
}
return RedirectToLocal(returnUrl, affiliatekey);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
if (await TryCreateOrAssocaiateUser(loginInfo, affiliatekey))
{
var user2 = controllerHelper.db.Users.Include("Affiliate").FirstOrDefault(i => i.Email == loginInfo.Email);
if (user2 != null)
{
affiliatekey = user2.Affiliate.Key;
}
return RedirectToLocal(returnUrl, affiliatekey);
}
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email, FullName = loginInfo.DefaultUserName });
}
}
private async Task<bool> TryCreateOrAssocaiateUser( ExternalLoginInfo info, string affiliatekey)
{
var affiliate = new ControllerHelper().GetAffiliate(affiliatekey);
var user = controllerHelper.db.Users.FirstOrDefault(i => i.Email.Equals(info.Email));
var result = new IdentityResult();
if (user == null)
{
user = new ApplicationUser { UserName = info.Email, FullName = info.DefaultUserName, Email = info.Email, AffiliateId = affiliate.Id, EmailConfirmed = true, LastLoginDateUtc = DateTime.UtcNow, EnableEmailNotifications = true, EnableSmsNotifications = true };
result = await UserManager.CreateAsync(user);
}
if (result.Succeeded || result.Errors.Count() == 0)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
}
else
{
return false;
}
return true;
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, string affiliatekey)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var affiliate = new ControllerHelper().GetAffiliate(affiliatekey);
var user = controllerHelper.db.Users.FirstOrDefault(i => i.Email.Equals(model.Email));
var result = new IdentityResult();
if (user == null)
{
user = new ApplicationUser { UserName = model.Email, FullName = model.FullName, Email = model.Email, AffiliateId = affiliate.Id, LastLoginDateUtc = DateTime.UtcNow, EnableSmsNotifications = true, EnableEmailNotifications = true };
result = await UserManager.CreateAsync(user);
}
if (result.Succeeded || result.Errors.Count() == 0)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl, affiliatekey);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff(string affiliatekey)
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Prayer", new { affiliatekey = affiliatekey });
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure(string affiliatekey)
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl, string affiliatekey)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Prayer", new { affiliatekey = affiliatekey });
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
//context.HttpContext.Session["WAKEUP"] = "NOW!";
//context.HttpContext.Session.RemoveAll();
//// this line fixed the problem with returing null
//context.RequestContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
}