public async Task<ActionResult> Register(RegisterVm Model) { Tuple<RegisterVm, LoginVm> badModel; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Model.EmailReg, Email = Model.EmailReg }; IdentityUserClaim _claim = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim(); _claim.ClaimType = "FullName"; _claim.ClaimValue = Model.FullName; _claim.UserId = user.Id; user.Claims.Add(_claim); ViewBag.FullName = Model.FullName; ViewBag.Email = user.Email; Random random = new Random(DateTime.Now.Day); StringBuilder strBuilder = new StringBuilder("!164"); for (int i = 0; i < 3; i++) { strBuilder.Append((char)random.Next(65, 90)); strBuilder.Append((char)random.Next(97, 122)); } string temporaryPassword = strBuilder.ToString(); var result = await UserManager.CreateAsync(user, temporaryPassword); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmailAndChangePassword", "Init", new { userId = System.Web.HttpUtility.UrlEncode(user.Id), code = System.Web.HttpUtility.UrlEncode(code) }, protocol: Request.Url.Scheme); try { ViewBag.Logo = Url.Content("~/Content/images/init/Logo.png", true); ViewBag.ConfirmReference = callbackUrl; string textmail = ViewToString("emailConfirmation", null); await UserManager.SendEmailAsync(user.Id, "Confirm your account", textmail);//"Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); } catch (SmtpException e1) { await UserManager.DeleteAsync(user); ViewBag.UnsuccessfulError = e1.Message; ModelState.AddModelError("", "Не удалось создать пользователя. " + e1.Message); badModel = new Tuple<RegisterVm, LoginVm>(Model, new LoginVm()); return View("Welcome", badModel); } return View("RegisterConfirmationSent"); } else { ModelState.AddModelError("", "Не удалось создать пользователя. " + result.Errors.First()); } } // If we got this far, something failed, redisplay form badModel = new Tuple<RegisterVm, LoginVm>(Model, new LoginVm()); return View("Index", badModel); }
private EF6.IdentityUserClaim CreateUserClaim(ApplicationUser user, Claim claim) { var userClaim = new EF6.IdentityUserClaim { UserId = user.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; return(userClaim); }
private async Task GrantResourceOwnerCredentialsFromFacebookToken(OAuthGrantResourceOwnerCredentialsContext context) { //Find External Token var facebookToken = getExternalToken(context); if (facebookToken == null) { throw new Exception("ExternalToken is null"); } //Get User Using FacebookToken var fb = new FacebookClient(facebookToken); Facebook.Me me = fb.Get <Facebook.Me>("me", new { fields = "id, name, email, gender, birthday, picture.type(large)" }); var User = userManager.FindByEmail(me.email); if (User == null) { var AccCtrl = new AccountController(HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>(), HttpContext.Current.GetOwinContext().GetUserManager <ApplicationSignInManager>()); User = await AccCtrl.CreateUser("User", me.email, me.email, null); } //Save fbtoken to db var db = new SoLoudContext(); //We need to refetch from db in order to be able to edit/add claims. If we dont the context is not tracking the Claim entities and changes will not save User = db.Users.Include("Claims").FirstOrDefault(x => x.Id == User.Id); var fbTokenClaim = User.Claims.FirstOrDefault(x => x.ClaimType == SoloudClaimTypes.FacebookAccessToken.ToString()); if (fbTokenClaim == null) { fbTokenClaim = new Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim() { ClaimType = SoloudClaimTypes.FacebookAccessToken.ToString() }; User.Claims.Add(fbTokenClaim); } fbTokenClaim.ClaimValue = AESThenHMAC.SimpleEncryptWithPassword(facebookToken, ConfigurationManager.AppSettings["EncryptionKey"].ToString()); db.SaveChanges(); //Create Token and return var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("UserName", User.UserName)); identity.AddClaim(new Claim("UserId", User.Id)); identity.AddClaim(new Claim(SoloudClaimTypes.FacebookAccessToken.ToString(), facebookToken)); //find user roles var UserRoles = User.Roles.Join(db.Roles, x => x.RoleId, r => r.Id, (x, r) => r.Name); if (UserRoles != null && UserRoles.Count() > 0) { identity.AddClaim(new Claim("Roles", UserRoles.Aggregate((acc, cur) => acc += "," + cur))); } var props = new AuthenticationProperties(new Dictionary <string, string> { { "User", JsonConvert.SerializeObject(User) } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); return; }
public Claim MakeClaim(EF6.IdentityUserClaim c) { return(new Claim(c.ClaimType, c.ClaimValue)); }