public AccountController() : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); try { if (!rm.RoleExists("admin")) { rm.Create(new IdentityRole("admin")); var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = new ApplicationUser() { UserName = "******" }; um.Create(user, "asdfgh"); UserLoginInfo info = new UserLoginInfo("Google", "https://www.google.com/accounts/o8/id?id=AItOawka6ZSrKNn7UY3ZUcjFRZMSLhMqQNKArWQ"); um.AddToRole(user.Id, "admin"); um.AddLogin(user.Id, info); } } catch (TimeoutException) { //CreateAdmin(); } }
protected void Page_Load() { // Process the result from an auth provider in the request ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { //MyUser user1 = MyUser.getUser(user.UserName, ""); //if(Session["UserId"]!=null && Convert.ToInt32(Session["UserId"].ToString())!=user1.userId) // Session.Add("UserId", user1.userId); IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { MyUser user1 = MyUser.getUser(user.UserName, ""); if (Session["UserId"] != null && Convert.ToInt32(Session["UserId"].ToString()) != user1.userId) Session.Add("UserId", user1.userId); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Process the result from an auth provider in the request ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("/Account/LogIn"); //Account/Login } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("/Account/LogIn"); //Account/Login } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("/Account/LogIn"); //Account/Login } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Zpracovat výsledek od poskytovatele ověřování v dané žádosti ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Použít kontrolu XSRF při propojování var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Обработка результата от поставщика проверки подлинности в запросе ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Применение проверки XSRF при связывании var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Ergebnis von einem Authentifizierungsanbieter in der Anforderung verarbeiten ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // XSRF-Überprüfung beim Verknüpfen anwenden var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Elaborare il risultato fornito da un provider di autenticazione nella richiesta ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Applicare il controllo XSRF durante il collegamento var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Procesar el resultado de un proveedor de autenticación en la solicitud ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Aplicar comprobación de Xsrf durante la vinculación var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Przetwórz wynik od dostawcy uwierzytelniania w żądaniu ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Zastosuj sprawdzanie pod kątem Xsrf podczas łączenia var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Sonucu istekteki bir yetki sağlayıcısından işle ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Bağlarken Xsrf denetimi uygula var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Traiter le résultat d'un fournisseur d'authentification dans la demande ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Effectuer une vérification xsrf lors de la liaison var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // 要求の認証プロバイダーからの結果を処理します ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
public void Register(UserInfo user, string password) { LoginEntity loginEntity = new LoginEntity(); loginEntity.UserId = user.UserId; loginEntity.UserName = user.UserName; loginEntity.IsCanLogin = true; UserBaseEntity userBaseEntity = new UserBaseEntity(); userBaseEntity.UserId = user.UserId; userBaseEntity.RealName = user.RealName; userBaseEntity.Email = user.Email; userBaseEntity.CardType = user.IdCardType; userBaseEntity.CardNumber = user.IdCardNumber; userBaseEntity.Mobile = user.Mobile; UserBalanceEntity balanceEntity = new UserBalanceEntity(); balanceEntity.UserId = user.UserId; balanceEntity.Balance = 0; balanceEntity.Freeze = 0; try { using (ILHDBTran tran = BeginTran()) { UserManager manager = new UserManager(tran); password = EncryptTool.MD5(password); manager.AddLogin(loginEntity, password); manager.AddUserBase(userBaseEntity); manager.AddBalance(balanceEntity); tran.Commit(); } } catch (Exception ex) { string errMsg = "注册新用户失败 - 系统异常,请联系系统管理员!"; throw HandleException(LogCategory.Register, errMsg, ex); } }
public IdentityUser CreateUserWithSocialProvider(UserLoginInfo login, ClaimsIdentity identity) { var userProfile = _userProfileSocialService.GetFromSocialProvider(login.LoginProvider, identity); if (string.IsNullOrEmpty(userProfile.Email)) { throw new Exception("Debes proveer un correo para crear tu cuenta."); } var user = new IdentityUser(GenerateUserName()) { Email = userProfile.Email }; var userCreationResult = _userManager.Create(user); _userManager.AddToRole(user.Id, "Client"); if (userCreationResult.Succeeded) { var userLoginResult = _userManager.AddLogin(user.Id, login); if (!userLoginResult.Succeeded) { foreach (var error in userLoginResult.Errors) { throw new Exception(error); } } } else { foreach (var error in userCreationResult.Errors) { throw new Exception(error); } } userProfile.UserId = user.Id; _userProfileRepository.Add(userProfile); _userProfileRepository.SaveChanges(); return(user); }
public async Task <HttpResponseMessage> ExternalLoginAsync(SocialLoginDTO userData) { var userStore = new UserStore <ApplicationUser>(new ApplicationDbContext()); var manager = new UserManager <ApplicationUser>(userStore); var existingUser = manager.FindByEmail(userData.Email); if (existingUser == null) { var user = new ApplicationUser(); user.UserName = (userData.Email).Split('@')[0]; user.FirstName = userData.FirstName; user.LastName = userData.LastName; user.Email = userData.Email; user.EmailConfirmed = true; user.CityID = userData.CityId; IdentityResult result = manager.Create(user); if (result.Succeeded) { manager.AddToRole(user.Id, "NormalUser"); var userLoginInfo = new UserLoginInfo(userData.Provider, userData.Id); manager.AddLogin(user.Id, userLoginInfo); List <string> rolename = manager.GetRoles(user.Id).ToList(); return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.OK, rolename)); } return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.BadRequest, "Failed")); } else { var userLogIn = manager.Find(new UserLoginInfo(userData.Provider, userData.Id)); if (userLogIn != null) { List <string> rolename = manager.GetRoles(userLogIn.Id).ToList(); return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.OK, rolename)); } else { return(HTTPBusinessLogic.SetHttpResponse(HttpStatusCode.BadRequest, "login Failed")); } } }
public ActionResult ExternalLoginCallback(string returnUrl) { AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); if (!result.IsSuccessful) { return(RedirectToAction("ExternalLoginFailure")); } // Sign in the user with this external login provider if the user already has a login var login = new UserLoginInfo(result.Provider, result.ProviderUserId); var user = UserManager.Find(login); if (user != null) { SignInManager.SignIn(user, false, false); return(RedirectToLocal(returnUrl)); } else if (User.Identity.IsAuthenticated) { user = GetUser(); var identityResult = UserManager.AddLogin(user.Id, login); if (identityResult.Succeeded) { return(RedirectToAction("Manage")); } return(RedirectToAction("Manage", new { Message = ManageMessageId.Error })); } else { // If the user does not have an account, then prompt the user to create an account string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId); ViewBag.ReturnUrl = returnUrl; ViewBag.ProviderDisplayName = result.Provider; return(View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData })); } }
public void CreateWithoutCommitingNHibernateTransactionShouldNotInsertRows() { var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(this._session)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(this._session)); using (var ts = _session.BeginTransaction()) { userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome1"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.Create(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); } var x2 = userManager.FindByEmail("*****@*****.**"); Assert.IsNull(x2); }
private void CreateAndLoginUser(string email) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = email }; IdentityResult result = manager.Create(user); if (result.Succeeded) { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnect"].ConnectionString; OleDbConnection c = new OleDbConnection(connectionString); c.Open(); OleDbCommand cmd = c.CreateCommand(); cmd.CommandType = CommandType.Text; // Create query cmd.CommandText = "INSERT INTO users VALUES ('" + email + "', 0, null, null)"; //execute query OleDbDataReader reader = cmd.ExecuteReader(); c.Close(); manager.SetEmail(user.Id, email); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, isPersistent: false); Response.Redirect("~/Pages/Dashboard"); return; } } AddErrors(result); }
public void FindByEmailAggregated() { var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(this._session)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(this._session)); userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.CreateAsync(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); this._session.Clear(); x = userManager.FindByEmail("*****@*****.**"); Assert.IsNotNull(x); Assert.AreEqual(2, x.Claims.Count); Assert.AreEqual(1, x.Roles.Count); Assert.AreEqual(1, x.Logins.Count); }
public void CreateWithoutCommitingTransactionScopeShouldNotInsertRows() { var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(this._session)); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(this._session)); using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { // session is not opened inside the scope so we need to enlist it manually ((System.Data.Common.DbConnection)_session.Connection).EnlistTransaction(System.Transactions.Transaction.Current); userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome1"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.Create(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); } var x2 = userManager.FindByEmail("*****@*****.**"); Assert.IsNull(x2); }
public ActionResult ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = AuthenticationManager.GetExternalLoginInfo(); if (info == null) { return(View(nameof(ExternalLoginFailure))); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = UserManager.Create(user); if (result.Succeeded) { result = UserManager.AddLogin(user.Id, info.Login); if (result.Succeeded) { SignInManager.SignIn(user, false, false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = new UserManager(); var user = new ApplicationUser() { UserName = userName.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { MyUser myuser = new MyUser(userName.Text, "", nameUser.Text, contactNo.Text, (UserType)Enum.Parse(typeof(UserType), userType.SelectedItem.Value)); int returncode = myuser.addUser(); //MyUser user1 = MyUser.getUser(userName.Text, ""); //if (Session["UserId"] != null && Convert.ToInt32(Session["UserId"].ToString()) != user1.userId) // Session.Add("UserId", user1.userId); IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
private void ConfigureGoogle(IAppBuilder app) { const string clientId = "648995939983-jhm6d50u9m7s7ls9ek0vbqt6nr60e2bu.apps.googleusercontent.com"; const string clientSecret = "Pba8xj8P1SwgYfiuBxScY514"; var options = new GoogleOAuth2AuthenticationOptions { ClientId = clientId, ClientSecret = clientSecret, Provider = new GoogleOAuth2AuthenticationProvider { OnAuthenticated = async context => { ExternalLoginInfo loginInfo = HttpContext.Current.GetOwinContext().Authentication.GetExternalLoginInfo(); // Retrieve the OAuth access token to store for subsequent API calls string accessToken = context.AccessToken; // Retrieve the name of the user in Google string googleName = context.Name; // Retrieve the user's email address string googleEmailAddress = context.Email; // You can even retrieve the full JSON-serialized user var userDetail = context.User; string id = (dynamic)context.Id; string email = (dynamic)context.Email; var userStore = MembershipTools.NewUserStore(); var userManager = new UserManager <User>(userStore); var currentUser = userManager.FindByEmail(email); if (currentUser == null) { var serializedUser = context.User; try { var user = new User() { Email = email, Name = context.GivenName, Surname = context.FamilyName, UserName = email.Substring(0, email.IndexOf('@')), }; await userManager.CreateAsync(user, StringHelpers.GetCode().Substring(0, 6)); userManager.AddToRole(user.Id, "User"); //currentUser.EmailConfirmed = true; //currentUser.Name = context.GivenName; //currentUser.Surname = context.FamilyName; //currentUser.RegisterDate = DateTime.Now; var avatar = userDetail.SelectToken("image").SelectToken("url").ToString(); avatar = avatar.Substring(0, avatar.IndexOf('?')); //currentUser.AvatarPath = avatar; var result = userManager.AddLoginAsync(user.Id, loginInfo.Login); } catch (Exception ex) { string x = ex.StackTrace.ToString(); } } else { var result = userManager.AddLogin(currentUser.Id, loginInfo.Login); } } } }; app.UseGoogleAuthentication(options); }
private void ConfigureFacebook(IAppBuilder app) { const string appId = "345283286312425"; const string appSecret = "447e03a0096467eb0b60483c415168d4"; var options = new FacebookAuthenticationOptions { AppId = appId, AppSecret = appSecret }; options.Scope.Add("email"); options.Provider = new FacebookAuthenticationProvider() { OnAuthenticated = async context => { var userDetail = context.User; string id = (dynamic)context.Id; string email = (dynamic)context.Email; var userStore = MembershipTools.NewUserStore(); var userManager = new UserManager <User>(userStore); var currentUser = userManager.FindByEmail(email); if (currentUser != null) { var serializedUser = context.User; try { currentUser.EmailConfirmed = true; currentUser.Name = ((dynamic)context.User).first_name.Value; currentUser.Surname = ((dynamic)context.User).last_name.Value; //currentUser.RegisterDate = DateTime.Now; var avatar = @"https://graph.facebook.com/" + id + "/picture?type=large"; var loginInfo = HttpContext.Current.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo != null) { var result = userManager.AddLogin(currentUser.Id, loginInfo.Login); } await userStore.UpdateAsync(currentUser); await userStore.Context.SaveChangesAsync(); } catch (Exception ex) { string x = ex.StackTrace.ToString(); } } else { var user = new User() { Email = email, Name = ((dynamic)context.User).first_name.Value, Surname = ((dynamic)context.User).last_name.Value, UserName = email.Substring(0, email.IndexOf('@')) }; userManager.Create(user, StringHelpers.GetCode().Substring(0, 6)); var loginInfo = HttpContext.Current.GetOwinContext().Authentication.GetExternalLoginInfo(); var result = userManager.AddLogin(user.Id, loginInfo.Login); } } }; app.UseFacebookAuthentication(options); }
private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = new UserManager(); var user = new ApplicationUser() { UserName = userName.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { try { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); string insertQuery = "insert into [ACCOUNT] ([name],[balance],[Account_Number]) values (@name1,@balance1,@account1)"; SqlCommand com = new SqlCommand(insertQuery, conn); com.Parameters.AddWithValue("@name1", user); com.Parameters.AddWithValue("@balance1", "100000000"); com.Parameters.AddWithValue("@account1", "1"); com.ExecuteNonQuery(); conn.Close(); } catch (Exception ex) { Response.Write("Error:" + ex.ToString()); } IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
public ActionResult ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl) { var appUser = new AppUser(); if (User.Identity.IsAuthenticated) { return(RedirectToLocal("~/")); } if (ModelState.IsValid) { var loginInfo = AuthManager.GetExternalLoginInfo(); if (loginInfo == null) { model.ExternLoginSucces = false; return(View(model)); } if (!string.IsNullOrEmpty(model.Email)) { appUser.UserName = model.Email; appUser.Email = model.Email; } else { model.ExternLoginSucces = false; return(View(model)); } var result = UserManager.Create(appUser); if (result.Succeeded) { bool res = authUserInfo.AddInfo(loginInfo, appUser.Id, loginInfo.Login.LoginProvider); if (!res) { model.ExternLoginSucces = res; ModelState.AddModelError("", "Во время сохранения аккаунта возникли ошибки!"); return(View("ExternalLoginConfirmation", model)); } result = UserManager.AddLogin(appUser.Id, loginInfo.Login); if (result.Succeeded) { appUser.EmailConfirmed = true; UserManager.AddToRole(appUser.Id, RoleConstant.RoleUser); result = UserManager.Update(appUser); if (result.Succeeded) { SignInManager.SignIn(appUser, false, false); } else { AddErrorsFromResult(result); } } else { AddErrorsFromResult(result); } } else { AddErrorsFromResult(result); } } else { ModelState.AddModelError("", "Во время регистрации возникли ошибки!"); return(View("ExternalLoginConfirmation", model)); } return(RedirectToLocal("~/")); }
public async Task Can_create_user_and_log_in() { const string username = "******"; const string userId = "user_id_1"; string password = Guid.NewGuid().ToString("n"); const string googleLogin = "******"; const string yahooLogin = "******"; var user = new SimpleAppUser { Id = userId, UserName = username }; using (var docStore = NewDocStore()) { using (var session = docStore.OpenAsyncSession()) { using (var mgr = new UserManager<SimpleAppUser>(new UserStore<SimpleAppUser>(session))) { IdentityResult result = mgr.Create(user, password); Assert.True(result.Succeeded); Assert.NotNull(user.Id); var res1 = mgr.AddLogin(user.Id, new UserLoginInfo("Google", googleLogin)); var res2 = mgr.AddLogin(user.Id, new UserLoginInfo("Yahoo", yahooLogin)); Assert.True(res1.Succeeded); Assert.True(res2.Succeeded); } await session.SaveChangesAsync(); } using (var session = docStore.OpenSession()) { var loaded = session.Load<SimpleAppUser>(user.Id); Assert.NotNull(loaded); Assert.NotSame(loaded, user); Assert.Equal(loaded.Id, user.Id); Assert.Equal(loaded.UserName, user.UserName); Assert.NotNull(loaded.PasswordHash); Assert.Equal(loaded.Logins.Count, 2); Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Google" && x.ProviderKey == googleLogin)); Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Yahoo" && x.ProviderKey == yahooLogin)); var loadedLogins = session.Advanced.LoadStartingWith<IdentityUserLogin>("IdentityUserLogins/"); Assert.Equal(loadedLogins.Length, 2); foreach (var login in loaded.Logins) { var loginDoc = session.Load<IdentityUserLogin>(Util.GetLoginId(login)); Assert.Equal(login.LoginProvider, loginDoc.Provider); Assert.Equal(login.ProviderKey, loginDoc.ProviderKey); Assert.Equal(user.Id, loginDoc.UserId); } } using (var session = docStore.OpenAsyncSession()) { using (var mgr = new UserManager<SimpleAppUser>(new UserStore<SimpleAppUser>(session))) { var userByName = mgr.Find(username, password); var userByGoogle = mgr.Find(new UserLoginInfo("Google", googleLogin)); var userByYahoo = mgr.Find(new UserLoginInfo("Yahoo", yahooLogin)); Assert.NotNull(userByName); Assert.NotNull(userByGoogle); Assert.NotNull(userByYahoo); Assert.Equal(userByName.Id, userId); Assert.Equal(userByName.UserName, username); // The Session cache should return the very same objects Assert.Same(userByName, userByGoogle); Assert.Same(userByName, userByYahoo); } await session.SaveChangesAsync(); } } }
public void CreateWithoutCommitingNHibernateTransactionShouldNotInsertRows() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session)); using (var ts = _session.BeginTransaction()) { userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome1"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.Create(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); } var x2 = userManager.FindByEmail("*****@*****.**"); Assert.IsNull(x2); }
public void fix() { using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { // ad info if (!newthreadcontext.TemplateDB.Any()) { var adinfo = migrateDB.TemplatesDB.Include("RecommendedInfo"); foreach (var i in adinfo) { var t = newthreadcontext.TemplateDB.Add(new AdInfoTemplate() { TemplateName = i.TemplateName, RecommendedInfo = new List <AdInfoString>() }); foreach (var x in i.RecommendedInfo) { t.RecommendedInfo.Add(new AdInfoString() { Name = x.Name }); } } newthreadcontext.SaveChanges(); } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.MiscInfoDB.Any()) { var make = migrateDB.MakeDB.ToList(); foreach (var i in make) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleMake" }); } var adtype = migrateDB.TypesDB.ToList(); foreach (var i in adtype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Value, Name = i.Name, Descriptor = "AdType" }); } var bodytype = migrateDB.BodyTypeDB.ToList(); foreach (var i in bodytype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Type, Descriptor = "VehicleBodyType" }); } var transmission = migrateDB.TransmissionDB.ToList(); foreach (var i in transmission) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleTransmission" }); } var drivetrain = migrateDB.DrivetrainDB.ToList(); foreach (var i in drivetrain) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleDrivetrain" }); } var condition = migrateDB.ConditionDB.ToList(); foreach (var i in condition) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleCondition" }); } var fueltype = migrateDB.FuelDB.ToList(); foreach (var i in fueltype) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "VehicleFuelType" }); } var priceinfo = migrateDB.PriceInfoDB.ToList(); foreach (var i in priceinfo) { newthreadcontext.MiscInfoDB.Add(new MiscInfo() { Value = i.Name, Descriptor = "PriceInfo" }); } newthreadcontext.SaveChanges(); } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.CategoryDB.Any()) { var cat = migrateDB.CategoryDB.Include("SubCategories.AdInfoTemplate").ToList(); foreach (var i in cat) { var currentcat = newthreadcontext.CategoryDB.Add(new Category() { Name = i.Name, TotalClassifiedAdsCount = i.TotalClassifiedAdsCount }); List <SubCategory> scl = new List <SubCategory>(); foreach (var j in i.SubCategories) { if (j.AdInfoTemplate != null) { var template = newthreadcontext.TemplateDB.SingleOrDefault(x => x.TemplateName.Equals(j.AdInfoTemplate.TemplateName)); scl.Add(new SubCategory() { Category = currentcat, Name = j.Name, stringId = j.stringId, AdInfoTemplate = template }); } else { scl.Add(new SubCategory() { Category = currentcat, Name = j.Name, stringId = j.stringId }); } } newthreadcontext.SubCategoryDB.AddRange(scl); } newthreadcontext.SaveChanges(); } } } if (!RoleManager.RoleExists("Admin")) { RoleManager.Create(new IdentityRole() { Name = "Admin" }); } if (!RoleManager.RoleExists("Banned")) { RoleManager.Create(new IdentityRole() { Name = "Banned" }); } if (!RoleManager.RoleExists("Moderator")) { RoleManager.Create(new IdentityRole() { Name = "Moderator" }); } if (!RoleManager.RoleExists("Premium")) { RoleManager.Create(new IdentityRole() { Name = "Premium" }); } if (!RoleManager.RoleExists("User")) { RoleManager.Create(new IdentityRole() { Name = "User" }); } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!newthreadcontext.CountryDB.Any()) { var trinidad = newthreadcontext.CountryDB.Add(new Country() { Name = "Trinidad" }); var tobago = newthreadcontext.CountryDB.Add(new Country() { Name = "Tobago" }); newthreadcontext.SaveChanges(); } if (!newthreadcontext.RegionDB.Any()) { var trinidad = newthreadcontext.CountryDB.SingleOrDefault(x => x.Name.Equals("Trinidad")); List <Region> trinR = new List <Region>() { new Region() { Country = trinidad, Name = "Port of Spain" }, new Region() { Country = trinidad, Name = "San Fernando" }, new Region() { Country = trinidad, Name = "Marabella" }, new Region() { Country = trinidad, Name = "Chaguanas" }, new Region() { Country = trinidad, Name = "Cunupia" }, new Region() { Country = trinidad, Name = "Endeavour" }, new Region() { Country = trinidad, Name = "Felicity" }, new Region() { Country = trinidad, Name = "Montrose" }, new Region() { Country = trinidad, Name = "Arima" }, new Region() { Country = trinidad, Name = "Point Fortin" }, new Region() { Country = trinidad, Name = "Guapo" }, new Region() { Country = trinidad, Name = "Techier" }, new Region() { Country = trinidad, Name = "Claxton Bay" }, new Region() { Country = trinidad, Name = "Diego Martin" }, new Region() { Country = trinidad, Name = "Maraval" }, new Region() { Country = trinidad, Name = "Westmoorings" }, new Region() { Country = trinidad, Name = "Penal" }, new Region() { Country = trinidad, Name = "Debe" }, new Region() { Country = trinidad, Name = "Moruga" }, new Region() { Country = trinidad, Name = "Princes Town" }, new Region() { Country = trinidad, Name = "Mayaro" }, new Region() { Country = trinidad, Name = "Rio Claro" }, new Region() { Country = trinidad, Name = "Guayaguayare" }, new Region() { Country = trinidad, Name = "Barataria" }, new Region() { Country = trinidad, Name = "Laventille" }, new Region() { Country = trinidad, Name = "Morvant" }, new Region() { Country = trinidad, Name = "St. Joseph" }, new Region() { Country = trinidad, Name = "San Juan" }, new Region() { Country = trinidad, Name = "Guaico" }, new Region() { Country = trinidad, Name = "Sangre Grande" }, new Region() { Country = trinidad, Name = "Toco" }, new Region() { Country = trinidad, Name = "Valencia" }, new Region() { Country = trinidad, Name = "Cedros" }, new Region() { Country = trinidad, Name = "Fyzabad" }, new Region() { Country = trinidad, Name = "La Brea" }, new Region() { Country = trinidad, Name = "Santa Flora" }, new Region() { Country = trinidad, Name = "Siparia" }, new Region() { Country = trinidad, Name = "Arouca" }, new Region() { Country = trinidad, Name = "Curepe" }, new Region() { Country = trinidad, Name = "Piarco" }, new Region() { Country = trinidad, Name = "St Augustine" }, new Region() { Country = trinidad, Name = "Trincity" }, new Region() { Country = trinidad, Name = "Tunapuna" }, new Region() { Country = trinidad, Name = "Couva" }, new Region() { Country = trinidad, Name = "Talparo" }, new Region() { Country = trinidad, Name = "Tabaquite" }, new Region() { Country = trinidad, Name = "Point Lisas" }, new Region() { Country = trinidad, Name = "Caroni" }, new Region() { Country = trinidad, Name = "Santa Cruz" }, new Region() { Country = trinidad, Name = "Freeport" } }; trinidad.Regions = trinR; trinidad.RegionCount = trinR.Count; newthreadcontext.SaveChanges(); var tobago = newthreadcontext.CountryDB.SingleOrDefault(x => x.Name.Equals("Tobago")); List <Region> tobaR = new List <Region>() { new Region() { Country = tobago, Name = "Charlotteville" }, new Region() { Country = tobago, Name = "Roxborough" }, new Region() { Country = tobago, Name = "Scarborough" }, new Region() { Country = tobago, Name = "Canaan" }, new Region() { Country = tobago, Name = "Plymouth" }, new Region() { Country = tobago, Name = "Moriah" } }; tobago.Regions = tobaR; tobago.RegionCount = tobaR.Count; newthreadcontext.SaveChanges(); } } } using (MigrationDbContext migrateDB = new MigrationDbContext()) { if (!UserManager.Users.Any()) { var userwithad = migrateDB.UserProfiles.ToList(); foreach (var user in userwithad) { ApplicationUser newuser = new ApplicationUser() { Email = user.Email, UserName = !String.IsNullOrEmpty(user.UserName) ? user.Email.Split('@').First() : user.UserName, StringId = user.StringId, PhoneNumber = user.ContactNumber }; var result = UserManager.Create(newuser); if (result.Succeeded) { string query = "SELECT green_kappakappa.webpages_Roles.RoleName FROM(green_kappakappa.webpages_Roles INNER JOIN green_kappakappa.webpages_UsersInRoles ON green_kappakappa.webpages_Roles.RoleId = green_kappakappa.webpages_UsersInRoles.RoleId) INNER JOIN UserProfile ON green_kappakappa.webpages_UsersInRoles.UserId = " + user.UserId; var role = migrateDB.Database.SqlQuery <string>(query).ToList(); UserManager.AddToRole(newuser.Id, role.First()); } } } } using (ApplicationDbContext newthreadcontext = new ApplicationDbContext()) { ICollection <ClassifiedAdOld> ads = new List <ClassifiedAdOld>(); using (MigrationDbContext migrateDB = new MigrationDbContext()) { ads = migrateDB.ClassifiedDB.Include("UserCreator").Include("Country").Include("Region").Include("AdInfo").Include("AdPhotos").Include("Category").Include("SubCategory").Include("Reports").ToList(); } if (!newthreadcontext.ClassifiedDB.Any()) { var config = new MapperConfiguration(r => { r.CreateMap <CategoryOld, Category>(); r.CreateMap <SubCategoryOld, SubCategory>() .ForMember(dest => dest.ClassifiedAds, opt => opt.Ignore()); r.CreateMap <InfoOld, Info>(); r.CreateMap <PhotoOld, Photo>(); r.CreateMap <AdPromotionOld, AdPromotion>(); }); IMapper mapper = config.CreateMapper(); foreach (var ad in ads) { var i = newthreadcontext.ClassifiedDB.Add(new ClassifiedAd()); i.AdType = ad.AdType; i.StringId = ad.StringId; i.ContactPrivacy = ad.ContactPrivacy; i.Description = ad.Description; i.EditCount = ad.EditCount; i.EditTimeStamp = ad.EditTimeStamp; i.FeaturedAdStatus = ad.FeaturedAdStatus; i.HtmlFreeDescription = ad.HtmlFreeDescription; i.MyProperty = ad.MyProperty; i.Price = ad.Price; i.PriceInfo = ad.PriceInfo; i.TimeStamp = ad.TimeStamp; i.Title = ad.Title; i.UrgentAdStatus = ad.UrgentAdStatus; i.UserContactEmail = ad.UserContactEmail; i.UserContactName = ad.UserContactName; i.UserContactPhone = ad.UserContactPhone; i.UserContactPhone2 = ad.UserContactPhone2; i.UserContactPhone3 = ad.UserContactPhone3; i.Views = ad.Views; var sc = newthreadcontext.SubCategoryDB.Include("Category").FirstOrDefault(x => x.stringId.Equals(ad.SubCategory.stringId)); i.SubCategory = sc; i.Category = sc.Category; var user = newthreadcontext.Users.FirstOrDefault(x => x.Email.Equals(ad.UserCreator.Email)); i.UserCreator = user; var region = newthreadcontext.RegionDB.Include("Country").FirstOrDefault(x => ad.Region.Name.Contains(x.Name)); i.Region = region; i.Country = region.Country; foreach (var ap in ad.AdPhotos) { var pho = new Photo() { AdListThumbnail = ap.AdListThumbnail, ClassifiedAd = i, ContentType = ap.ContentType, CountNum = ap.CountNum, FileName = ap.FileName, SetThumbnail = ap.SetThumbnail, StringId = ap.StringId }; pho.ClassifiedAd.AdPhotos.Add(pho); } foreach (var ai in ad.AdInfo) { var inf = new Info() { ClassifiedAd = i, Description = ai.Description, Name = ai.Name, IntDescription = ai.IntDescription }; inf.ClassifiedAd.AdInfo.Add(inf); } foreach (var rep in ad.Reports) { var crep = new ClassifiedAdReport() { ClassifiedAd = i, CreatedDate = rep.CreatedDate, OpenRequest = rep.OpenRequest, ReasonDescription = rep.ReasonDescription, ReasonTitle = rep.ReasonTitle, ReportingUser = rep.ReportingUser, Status = rep.Status }; crep.ClassifiedAd.Reports.Add(crep); } if (ad.Status == 0) { i.SubCategory.ClassifiedAdsCount++; i.Category.TotalClassifiedAdsCount++; } newthreadcontext.SaveChanges(); } } } using (MigrationDbContext migrateDB = new MigrationDbContext()) { var query = "SELECT green_kappakappa.webpages_OAuthMembership.Provider, green_kappakappa.webpages_OAuthMembership.ProviderUserId, UserProfile.Email FROM UserProfile INNER JOIN green_kappakappa.webpages_OAuthMembership ON UserProfile.UserId = green_kappakappa.webpages_OAuthMembership.UserId"; var logins = migrateDB.Database.SqlQuery <login>(query).ToList(); foreach (var login in logins) { var user = UserManager.FindByEmail(login.Email); UserManager.AddLogin(user.Id, new UserLoginInfo(login.Provider, login.ProviderUserId)); } } }
public void Can_create_user_and_log_in() { const string username = "******"; const string userId = "user_id_1"; string password = Guid.NewGuid().ToString("n"); const string googleLogin = "******"; const string yahooLogin = "******"; var user = new SimpleAppUser { Id = userId, UserName = username }; using (var docStore = NewDocStore()) { using (var session = docStore.OpenAsyncSession()) { using (var mgr = new UserManager <SimpleAppUser>(new UserStore <SimpleAppUser>(session))) { IdentityResult result = mgr.Create(user, password); Assert.True(result.Succeeded); Assert.NotNull(user.Id); var res1 = mgr.AddLogin(user.Id, new UserLoginInfo("Google", googleLogin)); var res2 = mgr.AddLogin(user.Id, new UserLoginInfo("Yahoo", yahooLogin)); Assert.True(res1.Succeeded); Assert.True(res2.Succeeded); } session.SaveChangesAsync(); } using (var session = docStore.OpenSession()) { var loaded = session.Load <SimpleAppUser>(user.Id); Assert.NotNull(loaded); Assert.NotSame(loaded, user); Assert.Equal(loaded.Id, user.Id); Assert.Equal(loaded.UserName, user.UserName); Assert.NotNull(loaded.PasswordHash); Assert.Equal(loaded.Logins.Count, 2); Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Google" && x.ProviderKey == googleLogin)); Assert.True(loaded.Logins.Any(x => x.LoginProvider == "Yahoo" && x.ProviderKey == yahooLogin)); var loadedLogins = session.Advanced.LoadStartingWith <IdentityUserLogin>("IdentityUserLogins/"); Assert.Equal(loadedLogins.Length, 2); foreach (var login in loaded.Logins) { var loginDoc = session.Load <IdentityUserLogin>(Util.GetLoginId(login)); Assert.Equal(login.LoginProvider, loginDoc.Provider); Assert.Equal(login.ProviderKey, loginDoc.ProviderKey); Assert.Equal(user.Id, loginDoc.UserId); } } using (var session = docStore.OpenAsyncSession()) { using (var mgr = new UserManager <SimpleAppUser>(new UserStore <SimpleAppUser>(session))) { var userByName = mgr.Find(username, password); var userByGoogle = mgr.Find(new UserLoginInfo("Google", googleLogin)); var userByYahoo = mgr.Find(new UserLoginInfo("Yahoo", yahooLogin)); Assert.NotNull(userByName); Assert.NotNull(userByGoogle); Assert.NotNull(userByYahoo); Assert.Equal(userByName.Id, userId); Assert.Equal(userByName.UserName, username); // The Session cache should return the very same objects Assert.Same(userByName, userByGoogle); Assert.Same(userByName, userByYahoo); } session.SaveChangesAsync(); } } }
public void FindByEmailAggregated() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session)); userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.CreateAsync(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); this._session.Clear(); x = userManager.FindByEmail("*****@*****.**"); Assert.IsNotNull(x); Assert.AreEqual(2, x.Claims.Count); Assert.AreEqual(1, x.Roles.Count); Assert.AreEqual(1, x.Logins.Count); }
public void CreateWithoutCommitingTransactionScopeShouldNotInsertRows() { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this._session)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this._session)); using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { // session is not opened inside the scope so we need to enlist it manually ((System.Data.Common.DbConnection)_session.Connection).EnlistTransaction(System.Transactions.Transaction.Current); userManager.Create(new ApplicationUser() { UserName = "******", Email = "*****@*****.**", EmailConfirmed = true }, "Welcome1"); var x = userManager.FindByEmail("*****@*****.**"); roleManager.Create(new IdentityRole("Admin")); userManager.AddClaim(x.Id, new Claim("role", "admin")); userManager.AddClaim(x.Id, new Claim("role", "user")); userManager.AddToRole(x.Id, "Admin"); userManager.AddLogin(x.Id, new UserLoginInfo("facebook", "1234")); } var x2 = userManager.FindByEmail("*****@*****.**"); Assert.IsNull(x2); }
private void CreateAndLoginUser() { if (!IsValid) { return; } var currentApplicationId = new ApplicationDbContext().Applications.SingleOrDefault(x => x.ApplicationName == "/").ApplicationId; var manager = new UserManager(); var user = new User() { UserName = Username.Text, ApplicationId = currentApplicationId, LoweredUserName = Username.Text.ToLower() }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/IdentityAccount/Login.aspx"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = new UserManager(); var user = new ApplicationUser() { UserName = userName.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); }
public Task <AuthenticationServiceResponse> CreateUser(UserModel model, bool isExternalLogin = false) { var userPosition = new List <UserPosition>(); var user = new ApplicationUser(); var result = new IdentityResult(); try { var exstUsr = UserManager.FindByEmail(model.Email); if (exstUsr == null) { Mapper.Map(model, user); user.CreatedDate = DateTime.UtcNow; if (isExternalLogin) { if (user.IndustryId.Equals(0)) { user.IndustryId = null; } result = UserManager.Create(user); result = UserManager.AddLogin(user.Id, new UserLoginInfo(model.LoginProvider, model.ProviderKey)); // Creating External User // model.UserPositions.ForEach(t => t.UserId = user.Id); //Mapper.Map(model.UserPositions, userPosition); //_unitOfWork.userPositionsRepository.InsertAll(userPosition); //_unitOfWork.Save(); } else { if (user.IndustryId.Equals(0)) { user.IndustryId = null; } result = UserManager.Create(user);// Creating Signup user SendEmail(user, MailSubject.CONFIRM_ACCOUNT); } Mapper.Map(user, model); if (result.Succeeded) { return(Task.FromResult(new AuthenticationServiceResponse() { Data = model, Success = result.Succeeded, Message = CommonConstants.EmailVerification })); } return(Task.FromResult(new AuthenticationServiceResponse() { Data = model, Success = result.Succeeded, Message = result.Errors.FirstOrDefault() })); } else { return(Task.FromResult(new AuthenticationServiceResponse() { Data = model, Success = false, Message = "Email already exist" })); } } catch (Exception ex) { throw ex; } }