Esempio n. 1
1
        public async Task SetupAsync()
        {
            _evnt = new EventViewModel
            {
                Title = "Title event",
                Description = "Test event",
                Start = "11:00",
                End = "14:27",
                Date = "2016-02-01"
            };

            var userViewModel = new LoginViewModel
            {
                Email = "*****@*****.**",
                Password = "******",
                RememberMe = false
            };
            var context = new DataContext();
            var manager = new UserManager(new UserStore(context));
            var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
            if (user == null)
            {
                await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
            }
            _calendarController = new CalendarController(context);

            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _calendarController.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _calendarController.AuthenticationManager = mockAuthenticationManager.Object;
        }
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            // password for jwmcpeak is asdlfkf@RAG04
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = await userManager.FindAsync(model.Username, model.Password);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "The user with the supplied credentials does not exist.");
                return View(model);
            }

            var authManager = HttpContext.GetOwinContext().Authentication;
            var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            authManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);

            return RedirectToAction("index", "home");
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
Esempio n. 4
0
 public async Task<string> GetAuthKey(string username, string password)
 {
     var store = new ApplicationDbContext();
     var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(store));
     var user =await UserManager.FindAsync(username, password);
     var key=Guid.NewGuid().ToString();
     user.Logins.Add(new IdentityUserLogin { LoginProvider="app",ProviderKey=key,UserId=user.Id});
     store.SaveChanges();
     return key;
 }
Esempio n. 5
0
		/// <summary>
		/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
		/// </summary>
		/// <param name="context">Contains information about the login session as well as the LTI request.</param>
		/// <param name="claims">Optional set of claims to add to the identity.</param>
		/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
		public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
		{
			// Find existing pairing between LTI user and application user
			var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
			var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
			var providerKey = context.LtiRequest.UserId;
			var login = new UserLoginInfo(loginProvider, providerKey);
			var user = await userManager.FindAsync(login);
			if (user == null)
			{
				var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
				await context.Options.Provider.GenerateUserName(usernameContext);
				if (string.IsNullOrEmpty(usernameContext.UserName))
				{
					return;
				}
				user = await userManager.FindByNameAsync(usernameContext.UserName);
				if (user == null)
				{
					user = new ApplicationUser { UserName = usernameContext.UserName };
					var result = await userManager.CreateAsync(user);
					if (!result.Succeeded)
					{
						return;
					}
				}
				// Save the pairing between LTI user and application user
				await userManager.AddLoginAsync(user.Id, login);
			}

			// Create the application identity, add the LTI request as a claim, and sign in
			var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
			identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
					new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
			if (claims != null)
			{
				foreach (var claim in claims)
				{
					identity.AddClaim(claim);
				}
			}
			context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);

			// Redirect to original URL so the new identity takes affect
			context.RedirectUrl = context.LtiRequest.Url.ToString();
		}
        // GET: ClaimsIdentityFactory
        public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
        {
            var context = new MyDbContext();
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<ApplicationUser>();

            // Create a User to SignIn
            var user = await userManager.FindAsync(model.UserName, model.Password);

            //SignIn the User by generating a ClaimsIdentity            
            var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            // This claimsIdentity should have a claim called LastLoginTime
            var authManager = HttpContext.GetOwinContext().Authentication;
            authManager.SignIn(claimsIdentity);
            
            return RedirectToLocal(returnUrl);
        }
Esempio n. 7
0
        public async void CreatesFindsAndDeletes()
        {
            var username = "******";
            var user     = new IdentityUser(username);

            Console.WriteLine("GUID: {0}", user.Id);
            var password = "******";
            var sut      = new UserManager();

            await sut.CreateAsync(user, password);

            var actualUser = await sut.FindAsync(username, password);

            Assert.IsNotNull(actualUser);
            Assert.AreEqual(user.Id, actualUser.Id);

            await sut.DeleteAsync(user);
        }
Esempio n. 8
0
        public async Task <IHttpActionResult> LoginJwt(LoginModel loginModel)
        {
            var user = await UserManager.FindAsync(loginModel.UserName, loginModel.Password);

            if (user == null)
            {
                return(Ok(new ResponseBase <JObject>
                {
                    statusCode = 400,
                    userMessage = "Invalid email address or password.",
                    devMessage = "Invalid email address or password.",
                }));
            }

            var token = TokenManager.GenerateToken(user.UserName);

            return(Ok(token));
        }
Esempio n. 9
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);

                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);

                    return(RedirectToLocal(returnUrl));
                }
                ModelState.AddModelError("", "Invalid username or password.");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public virtual async Task <ExternalAuthenticateResult> AuthenticateExternalAsync(string subject, ExternalIdentity externalUser)
        {
            if (externalUser == null)
            {
                throw new ArgumentNullException("externalUser");
            }

            var user = await userManager.FindAsync(new UserLoginInfo(externalUser.Provider.Name, externalUser.ProviderId));

            if (user == null)
            {
                return(await ProcessNewExternalAccountAsync(externalUser.Provider.Name, externalUser.ProviderId, externalUser.Claims));
            }
            else
            {
                return(await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider.Name, externalUser.ProviderId, externalUser.Claims));
            }
        }
Esempio n. 11
0
        public async Task <ActionResult> Login(LoginViewModel details, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await UserManager.FindAsync(details.Name, details.Password);

                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid name or password.");
                }
                //
                else
                {
                    //If the FindAsync method does return an AppUser object,
                    //then I need to create the cookie that the browser will send in subsequent requests to show they are authenticated. H
                    ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    ident.AddClaims(LocationClaimsProvider.GetClaims(ident));

                    ident.AddClaims(ClaimsRoles.CreateRolesFromClaims(ident));

                    //I will use Email-type claim to identify users (I did this in Global.asax/Application_Start()),
                    //external authority will give me this claim
                    //but LOCAL AUTHORIRY will not, so I manually create one
                    ident.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", user.Email));

                    //invalidate any existing authentication cookies and create the new one
                    AuthManager.SignOut();
                    AuthManager.SignIn(
                        new AuthenticationProperties
                    {
                        //Keep the cookie persistent,
                        //the user doesn't have to authenticate again when starting a new session
                        IsPersistent = false
                    },
                        ident);
                    // Migrate the user's shopping cart
                    Session["CartId"] = user.UserName;
                    MigrateShoppingCart(user.UserName);
                }
            }
            ViewBag.returnUrl = returnUrl;
            return(View(details));
        }
Esempio n. 12
0
        public async Task <IHttpActionResult> Login(Auth auth)
        {
            try
            {
                var appUser = await _userManager.FindAsync(auth.UserName, auth.Password);

                if (appUser != null && appUser.Status == Enum.Status.Active)
                {
                    if (appUser.IsInRole(Enum.Role.Dealer))
                    {
                        var dealer = _dealerServices.GetByUserId(appUser.Id);
                        if (!dealer.Enable)
                        {
                            return(Content(HttpStatusCode.Forbidden, "This dealer is disabled"));
                        }
                    }

                    var isRememberMe = true;
                    Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    Authentication.SignIn(new AuthenticationProperties {
                        IsPersistent = isRememberMe
                    },
                                          await appUser.GenerateUserIdentityAsync(_userManager, DefaultAuthenticationTypes.ApplicationCookie, appUser));


                    return(Ok(new
                    {
                        data = new
                        {
                            user = appUser,
                            token = Guid.NewGuid().ToString()
                        }
                    }));
                }
                return(Ok(new
                {
                    data = new { error = "error" }
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            var user = await UserManager.FindAsync(loginInfo.Login);

            // Logar caso haja um login externo e já esteja logado neste provedor de login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);

            switch (result)
            {
            case SignInStatus.Success:
                var userext = UserManager.FindByEmailAsync(user.Email);
                await SignInAsync(userext.Result, false);

                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                // Se ele nao tem uma conta solicite que crie uma

                var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                var email            = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:email").Value;
                var firstName        = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:first_name").Value;
                var lastName         = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == "urn:facebook:last_name").Value;

                ViewBag.ReturnUrl     = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email, LastName = lastName, Name = firstName
                }));
            }
        }
Esempio n. 14
0
        public async Task <ActionResult> Create(LoginViewModel loginModel, string returnAddress)
        {
            if (ModelState.IsValid)
            {
                UserManager <ApplicationUser> userManager =
                    new UserManager <ApplicationUser>(new UserStore());

                var user = await userManager.FindAsync(loginModel.UserName, loginModel.Password);

                if (user != null)
                {
                    HttpContext.GetOwinContext().Authentication.SignOut(
                        DefaultAuthenticationTypes.ExternalCookie);

                    var identity = await userManager.CreateIdentityAsync(
                        user,
                        DefaultAuthenticationTypes.ApplicationCookie);

                    HttpContext.GetOwinContext().Authentication.SignIn(
                        new AuthenticationProperties()
                    {
                        IsPersistent = loginModel.RememberMe
                    },
                        identity);

                    if (Url.IsLocalUrl(returnAddress))
                    {
                        return(Redirect(returnAddress));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Orders"));
                    }
                }
                else
                {
                    ModelState.AddModelError(
                        string.Empty,
                        "Invalid user name or password.");
                }
            }
            return(View(loginModel));
        }
Esempio n. 15
0
        public async Task <ActionResult> LogIn(UsuarioViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            var user = await userManager.FindAsync(model.Email, model.Password);

            if (user != null)
            {
                var identity = await userManager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                GetAuthenticationManager().SignIn(identity);
                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }
            ModelState.AddModelError("", "Usuário e/ou Senha inválidos");
            return(View());
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userStore = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var manager   = new UserManager <ApplicationUser>(userStore);
            var user      = await manager.FindAsync(context.UserName, context.Password);

            if (user != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("Username", user.UserName));
                identity.AddClaim(new Claim("Email", user.Email));
                identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
                context.Validated(identity);
            }
            else
            {
                return;
            }
        }
        public async Task <IdentityResult> SignInUserLoginAsync(LoginViewModel model)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                IsolationLevel = IsolationLevel.RepeatableRead
            }, TransactionScopeAsyncFlowOption.Enabled))
            {
                var result = IdentityResult.Failed();
                try
                {
                    var password = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(model.Password));
                    var user     = await UserManager.FindAsync(model.UserName, password);

                    if (user != null)
                    {
                        result = IdentityResult.Success;
                        //var user = new
                        //{
                        //    UserId = Guid.NewGuid().ToString("n"),
                        //    UserName = model.UserName
                        //};

                        //var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                        //identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserId, ClaimValueTypes.String, DefaultAuthenticationTypes.ApplicationCookie));
                        //identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName, ClaimValueTypes.String, DefaultAuthenticationTypes.ApplicationCookie));
                        //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.IsPersistent }, identity);
                        //return RedirectToLocal(returnUrl);

                        //var claimsIdentity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                        await SignInManager.SignInAsync(user, isPersistent : model.IsPersistent, rememberBrowser : false);
                    }
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    result = IdentityResult.Failed(ex.Message);
                }
                finally
                {
                }
                return(result);
            }
        }
Esempio n. 18
0
        public async Task <ActionResult> IniciarSesion(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);

                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);
                }
                else
                {
                    ModelState.AddModelError("", "Usuario no registrado.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task FindAsync_ShouldReturnNull_WhenGivenCredentialsAreNotValid()
        {
            // arrange
            var user = new ApplicationUser {
                Username = Username, Password = Password
            };

            _userRepository.GetUserAsync(Username)
            .Returns(user);
            _passwordHasher.VerifyHashedPassword(Arg.Any <string>(), Arg.Any <string>())
            .ReturnsForAnyArgs(false);

            // act
            var userManager = new UserManager(_userRepository, _passwordHasher);
            var result      = await userManager.FindAsync(Username, Password);

            // assert
            result.Should().BeNull();
        }
Esempio n. 20
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var userStore = new UserStore<ApplicationUser>(new DataContext());
            var userManager = new UserManager<ApplicationUser>(userStore);
        var user = await  userManager.FindAsync(model.Email, model.Password);
            if (user != null)
            {
                ModelState.AddModelError(string.Empty, "Пользователь существует");
                return View(model);
            }

            user = new ApplicationUser { UserName = model.Email, Email = model.Email };
           await userManager.CreateAsync(user, model.Password);
            return RedirectToAction("Index", "Home");
        }
Esempio n. 21
0
        public async Task <ActionResult> GoogleLoginCallback(string returnUrl)
        {
            ExternalLoginInfo loginInfo = await AuthManager.GetExternalLoginInfoAsync();

            AppUser user = await UserManager.FindAsync(loginInfo.Login);    //檢查user 是否為第一次登入,若為是的話則回傳null

            if (user == null)
            {
                user = new AppUser
                {
                    Email     = loginInfo.Email,
                    UserName  = loginInfo.DefaultUserName,
                    CityID    = 1,
                    CountryID = 1
                };  //為該user 創建一個新的資料存到DB
                IdentityResult result = await UserManager.CreateAsync(user);

                if (!result.Succeeded)
                {
                    return(View("Error", result.Errors));
                }
                else
                {
                    result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                    if (!result.Succeeded)
                    {
                        return(View("Error", result.Errors));
                    }
                }
            }

            ClaimsIdentity ident = await UserManager.CreateIdentityAsync(user,
                                                                         DefaultAuthenticationTypes.ApplicationCookie);

            //ident.AddClaims(loginInfo.ExternalIdentity.Claims); //複製由Google 提供的Claims
            ident.AddClaims(ClaimsRoles.CreateRoleForGoogle());
            AuthManager.SignIn(new AuthenticationProperties
            {
                IsPersistent = false
            }, ident);
            return(Redirect(returnUrl ?? "/"));
        }
Esempio n. 22
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            ApplicationUser user = await manager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await manager.CreateIdentityAsync(user, "JWT");

            var ticket = new AuthenticationTicket(oAuthIdentity, null);

            context.Validated(ticket);
        }
Esempio n. 23
0
        public async Task <User> GetUser(string userName, string password)
        {
            ApplicationUser applicationUser = await UserManager.FindAsync(userName, password);

            if (applicationUser != null)
            {
                return(new User()
                {
                    FirstName = applicationUser.UserProfile.FirstName,
                    LastName = applicationUser.UserProfile.LastName,
                    Email = applicationUser.Email,
                    FullName = applicationUser.UserProfile.FullName,
                    Id = applicationUser.UserProfile.Id,
                    //ProfileImage = applicationUser.UserProfile.ProfileImage,
                    ProfileImageString = Request.GetFileUrl((int)FileType.Profile, applicationUser.UserProfile.ProfileImageString)
                });
            }
            return(null);
        }
Esempio n. 24
0
        public async Task <ActionResult> Login(Login login_)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = await UserManager.FindAsync(login_.Email, login_.Password);

                if (user != null)
                {
                    List <Claim> claims = new List <Claim>();
                    claims.Add(new Claim(ClaimTypes.NameIdentifier, login_.Email)); //, user.FirstName,user.LastName));
                    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationManager.SignIn(identity);

                    if (AuthenticationManager.AuthenticationResponseGrant.Identity.IsAuthenticated)
                    {
                        DbLevel   NW   = new DbLevel();
                        Employees empl = NW.GetEmployee(user);

                        if (empl != null)
                        {
                            TempData["Message"] = @"Welcome" + empl.FirstName + "!";
                            return(RedirectToAction("Orders", "Edit", new { userID = user.Id }));
                        }
                        else
                        {
                            TempData["Message"] = @"Something werid happened. No employee.";
                            return(View("Register", "Validation"));
                        }
                    }
                    else
                    {
                        TempData["Message"] = @"User not signed in";
                    }
                }
                else
                {
                    TempData["Message"] = @"Wrong password or username";
                }
            }

            login_.Message = TempData["Message"] as string;
            return(View(login_));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // to validate user for login
            var userStore = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var manager   = new UserManager <ApplicationUser>(userStore);
            var user      = await manager.FindAsync(context.UserName, context.Password);

            if (user != null)
            {
                //if (user.EmailConfirmed)
                //{
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("Username", user.UserName));
                identity.AddClaim(new Claim("Email", user.Email));
                identity.AddClaim(new Claim("FirstName", user.FirstName));
                identity.AddClaim(new Claim("LastName", user.LastName));
                identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
                var userRoles = manager.GetRoles(user.Id);
                foreach (string roleName in userRoles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, roleName));
                }
                //return data to client
                var additionalData = new AuthenticationProperties(new Dictionary <string, string> {
                    {
                        "role", Newtonsoft.Json.JsonConvert.SerializeObject(userRoles)
                    }
                });
                var token = new AuthenticationTicket(identity, additionalData);
                context.Validated(token);
                // }
                //else
                //{
                //    context.SetError("invalid_grant", "Account pending approval");
                //    return;
                //}
            }
            else
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                return;
            }
        }
Esempio n. 26
0
        public async Task <ActionResult> LogIn(LogInViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = await userManager.FindAsync(model.UserName, model.Password);

            if (user != null)
            {
                await SignIn(user);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            ModelState.AddModelError("", "Неверный логин или пароль");
            return(View());
        }
Esempio n. 27
0
        protected virtual async Task <ShaLoginResult <TTenant, TUser> > LoginAsyncInternal(UserLoginInfo login, string tenancyName)
        {
            if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty())
            {
                throw new ArgumentException("login");
            }

            //Get and check tenant
            TTenant tenant = null;

            if (!MultiTenancyConfig.IsEnabled)
            {
                tenant = await GetDefaultTenantAsync();
            }
            else if (!string.IsNullOrWhiteSpace(tenancyName))
            {
                tenant = await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);

                if (tenant == null)
                {
                    return(new ShaLoginResult <TTenant, TUser>(ShaLoginResultType.InvalidTenancyName));
                }

                if (!tenant.IsActive)
                {
                    return(new ShaLoginResult <TTenant, TUser>(ShaLoginResultType.TenantIsNotActive, tenant));
                }
            }

            int?tenantId = tenant == null ? (int?)null : tenant.Id;

            using (UnitOfWorkManager.Current.SetTenantId(tenantId))
            {
                var user = await UserManager.FindAsync(tenantId, login);

                if (user == null)
                {
                    return(new ShaLoginResult <TTenant, TUser>(ShaLoginResultType.UnknownExternalLogin, tenant));
                }

                return(await CreateLoginResultAsync(user, tenant));
            }
        }
Esempio n. 28
0
        [ValidateAntiForgeryToken]//表示用于阻止伪造请求的特性
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);

                if (user != null)
                {
                    await SignInAsync(user, model.RemeberMe);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
            return(View(model));
        }
Esempio n. 29
0
        public async Task <ActionResult> LogIn([Bind(Include = "UserName,Password,RememberMe")] LogIn login)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(login.UserName, login.Password);

                if (user != null)
                {
                    await SignInAsync(user, login.RememberMe);
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }

                //return RedirectToAction("Index", "Home");
            }
            return(RedirectToAction("Index", "Home"));
        }
        private async Task <ActionResult> RedirectToLocalAsync(string returnUrl, LoginViewModel model)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            ApplicationUser user = await UserManager.FindAsync(model.UserName, model.Password);

            //get imagepath from the user..
            UnitOfWork _unitOfWork = new UnitOfWork(new ApplicationDbContext());

            var fullUserData = _unitOfWork.UserRepositry.GetUserWithProjectsAndTasksAndRolesAndFilesAndFinanicalWithFilesWithPayments(user.Id);

            fullUserData.MyFiles = new List <MyUserFile>();

            // Redirect to User landing page on SignIn, according to Role
            if ((UserManager.IsInRole(user.Id, "Admin")))
            {
                //send image user to put it in loagin partial
                if (fullUserData.MyFiles.Count != 0)
                {
                    if (fullUserData.MyFiles.LastOrDefault(f => f.MyFileType == MyFileType.Photo).FileName != null)
                    {
                        Session["imgPath"] = fullUserData.MyFiles.LastOrDefault(f => f.MyFileType == MyFileType.Photo).FileName;
                    }
                }

                return(RedirectToAction("Index", "Admin"));
            }
            else
            {
                if (fullUserData.MyFiles.Count != 0)
                {
                    if (fullUserData.MyFiles.LastOrDefault(f => f.MyFileType == MyFileType.Photo).FileName != null)
                    {
                        Session["imgPath"] = fullUserData.MyFiles.LastOrDefault(f => f.MyFileType == MyFileType.Photo).FileName;
                    }
                }

                return(RedirectToAction("ShowTaskForEmployee", "TTask"));
            }
        }
        protected override async Task <IPrincipal> AuthenticateAsync(string userName, string password, CancellationToken cancellationToken)
        {
            UserManager <ApplicationUser> userManager = CreateUserManager();

            cancellationToken.ThrowIfCancellationRequested(); // Unfortunately, UserManager doesn't support CancellationTokens.
            ApplicationUser user = await userManager.FindAsync(userName, password);

            if (user == null)
            {
                // No user with userName/password exists.
                return(null);
            }

            // Create a ClaimsIdentity with all the claims for this user.
            cancellationToken.ThrowIfCancellationRequested(); // Unfortunately, IClaimsIdenityFactory doesn't support CancellationTokens.
            ClaimsIdentity identity = await userManager.ClaimsIdentityFactory.CreateAsync(userManager, user, "Basic");

            return(new ClaimsPrincipal(identity));
        }
        public async Task <IHttpActionResult> DeleteAccount([FromBody] string Password)
        {
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (Password == null)
            {
                return(BadRequest("Provide Password."));
            }
            var user1 = await UserManager.FindAsync(user.Email, Password);

            IdentityResult result = await UserManager.DeleteAsync(user1);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Esempio n. 33
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.UserName, model.Password);

                if (model.UserName.IsValidEmail())
                {
                    var userByEmail = await UserManager.FindByEmailAsync(model.UserName);

                    if (userByEmail == null)
                    {
                        ModelState.AddModelError("", "Invalid username or password.");
                        return(View(model));
                    }
                    model.UserName = userByEmail.UserName;
                    user           = await UserManager.FindAsync(userByEmail.UserName, model.Password);
                }
                if (user != null)
                {
                    var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

                    switch (result)
                    {
                    case SignInStatus.Success:
                        return(RedirectToLocal(returnUrl));

                    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));
                    }
                }
                ModelState.AddModelError("", "Invalid username or password.");
            }
            return(View(model));
        }
Esempio n. 34
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            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:

                //return RedirectToLocal(returnUrl);
                var user = await UserManager.FindAsync(model.Email, model.Password);

                if (user.Forcechangpassword == true)
                {
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        returnUrl = "/Messages";
                    }
                    ViewBag.ReturnUrl = returnUrl;
                    return(RedirectToAction("Manage", new { Message = ManageMessageId.FirstTimeLogin, ReturnUrl = returnUrl }));
                }
                return(RedirectToLocal(returnUrl));



            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));
            }
        }
Esempio n. 35
0
            //set token
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

                //client is null get all
                if (allowedOrigin == null)
                {
                    allowedOrigin = "*";
                }
                //add hearder token
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
                //create new AppicationUser
                UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <UserManager <ApplicationUser> >();
                ApplicationUser user;

                try
                {
                    //Find user and pass
                    user = await userManager.FindAsync(context.UserName, context.Password);

                    if (user != null)
                    {
                        //create memory contains variable
                        ClaimsIdentity identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ExternalBearer);

                        context.Validated(identity);
                    }
                    else
                    {
                        //show message
                        context.SetError("invalid_grant", "Tài khoản hoặc mật khẩu không đúng.'");
                        context.Rejected();
                    }
                }
                catch
                {
                    // Could not retrieve the user due to error.
                    context.SetError("server_error");
                    context.Rejected();
                    return;
                }
            }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await UserManager.FindAsync(model.Email, model.Password);

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }

            if (!user.EmailConfirmed)
            {
                ModelState.AddModelError("", "Email not verified.  Please check your email inbox.");
                return(View(model));
            }

            // This doen't count login failures towards lockout only two factor authentication
            // To enable password failures to trigger lockout, change to shouldLockout: true
            var result = await SignInHelper.PasswordSignIn(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Esempio n. 37
0
        public async Task <ResultWithData <string> > GetAuthTokenAsync(string email, string password)
        {
            var result = new ResultWithData <string>();

            try
            {
                ApplicationUser appUser;
                var             appUserByEmail = await UserManager.FindByEmailAsync(email);

                if (appUserByEmail != null)
                {
                    appUser = await UserManager.FindAsync(appUserByEmail.UserName, password);
                }
                else
                {
                    throw new Exception("Invalid login or password.");
                }

                if (appUser == null)
                {
                    throw new Exception("Invalid login or password.");
                }

                var token = appUser.Token;

                if (String.IsNullOrEmpty(token))
                {
                    throw new Exception("Invalid auth token.");
                }

                result.ResultData = token;
                result.Success    = true;
            }
            catch (Exception ex)
            {
                result.Success    = false;
                result.Message    = ex.Message;
                result.StackTrace = ex.StackTrace;
            }

            return(result);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = new UserManager<User>(new UserStore<User>(new DatabaseContext()));

            var user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var oAuthIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
            var cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            var properties = CreateProperties(user.UserName);
            var ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Esempio n. 39
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var userStore = new UserStore<ApplicationUser>(new DataContext());
            var userManager = new UserManager<ApplicationUser>(userStore);
            var user = await userManager.FindAsync(model.Email, model.Password);
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Пользователь с такой комбинацией пароля и логина не существует");
                return View(model);
            }
            var authManager = HttpContext.GetOwinContext().Authentication;
            var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            authManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);

            return RedirectToLocal(returnUrl);
        }
		public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {

			context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

			AuthContext _ctx = new AuthContext();
			using (UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))) {
				IdentityUser user = await _userManager.FindAsync(context.UserName, context.Password);

				if (user == null) {
					context.SetError("invalid_grant", "The user name or password is incorrect.");
					return;
				}
			}

			var identity = new ClaimsIdentity(context.Options.AuthenticationType);
			identity.AddClaim(new Claim("sub", context.UserName));
			identity.AddClaim(new Claim("role", "user"));
			identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

			context.Validated(identity);

		}
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // カスタマイズのポイント:
                //   UserManagerのインスタンス作成時、
                //     型引数:カスタマイズしたユーザー情報
                //     コンストラクタの引数:カスタマイズしたユーザストアのインスタンス
                //   をそれぞれ渡す
                var userManager = new UserManager<MyAppUser>(new MyAppUserStore());

                // カスタマイズのポイント:
                //   パスワードのハッシュ化アルゴリズムとして、IPasswordHasherを実装したカスタムクラスのインスタンスを設定
                userManager.PasswordHasher = new MyPasswordHasher();

                var user = await userManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    var authentication = this.HttpContext.GetOwinContext().Authentication;
                    var identify = await userManager.CreateIdentityAsync(
                        user,
                        DefaultAuthenticationTypes.ApplicationCookie);
                    authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identify);

                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "ログインIDまたはパスワードが無効です。");
                    
                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = await userManager.FindAsync(model.Username, model.Password);

            if (user != null)
            {
                ModelState.AddModelError(string.Empty, "The user already exists.");
                return View(model);
            }

            user = new IdentityUser { UserName = model.Username, Email = model.Email };

            await userManager.CreateAsync(user, model.Password);

            return RedirectToAction("index", "home");
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var dbContext = new InstantDeliveryContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(dbContext));
                User user = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                    OAuthDefaults.AuthenticationType);
                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                    CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }


            List<Tenant> tenants = new List<Tenant>();
            tenants.Add(new Tenant() { Id = 1, Name = "K Force", DbContext = "KforceDB", Email = "*****@*****.**" });
            tenants.Add(new Tenant() { Id = 2, Name = "Sudeep Company", DbContext = "SudeepDB", Email = "*****@*****.**" });

            string dbContext = tenants.First(x => x.Id == model.TenantId).DbContext;

            ApplicationDbContext _db= new ApplicationDbContext(dbContext);
            UserManager<ApplicationUser> _myUserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_db));

            var user = await _myUserManager.FindAsync("tcadmin", model.Password);
            if (user != null)
            {
                var claim = await _myUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, claim);
                return RedirectToAction("Index", "Admin");
            }


            //_myUserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            // 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: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    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);
            //}
            ViewData["Tenants"] = (from t in tenants
                                   select new SelectListItem()
                                   {
                                       Text = t.Name,
                                       Value = t.Id.ToString()
                                   }).ToList();
            return View(model);
        }
Esempio n. 45
0
		public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
			using(var db = new Contexto(options.ConnectionString)) {
				
				if(!db.Users.Any()) {
					
					foreach(var u in users) {
						var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
						var response = await userManager.CreateAsync(entity, u.Password);
						
						if(!response.Succeeded) {
							throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
						}
						else {
							
							var user = await userManager.FindAsync(u.Username,u.Password);
							foreach(var c in u.Claims) {

								await userManager.AddClaimAsync(user.Id,c);
							}
														
							await userManager.UpdateAsync(user);
						}
					}
					db.SaveChanges();
				}
			}
		}
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //try { 
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

            if (allowedOrigin == null) allowedOrigin = "*";

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            user.Roles.ToList().ForEach(r =>
            {
                var role = roleManager.FindById(r.RoleId);
                identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); 
            });
            
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            //}
            //catch (Exception ex)
            //{
            //    throw;
           // }
        }
        public async Task<JsonData> Login(LoginModel model)
        {
            try
            {
                using (var db = new DataContext())
                {
                    var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));

                    //get the user by the email address
                    var us = new UserRepo().GetUserByName(model.UserName, db);
                    if (us == null) throw new Exception("Please check the login details");

                    var user = await userMan.FindAsync(us.UserName, model.Password);
                    if (user == null) throw new Exception("Please check the login details");

                    if (!user.IsActive) throw new Exception("You can not login because your user is not active");

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    var identity = await userMan.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, identity);

                    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

                    return DataHelpers.ReturnJsonData(user, true, token);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
Esempio n. 48
-6
        public async Task SetupAsync()
        {
            _userViewModel = new LoginViewModel
            {
                Email = "*****@*****.**",
                Password = "******",
                RememberMe = false
            };
            var context = new DataContext();
            _manager = new UserManager(new UserStore(context));
            _controller = new AccountController(_manager);

            var user = await _manager.FindAsync(_userViewModel.Email, _userViewModel.Password);
            if (user == null)
            {
                await _manager.CreateAsync(new User { Email = _userViewModel.Email, UserName = _userViewModel.Email }, _userViewModel.Password);
            }
            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _controller.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _controller.AuthenticationManager = mockAuthenticationManager.Object;
        }