private void RegistUserAndIssueAuthCookie(AuthenticationResult result) { var salt = ConfigurationManager.AppSettings["SaltOfUserID"]; var user = new QuizWebApp.Models.User { UserId = GetHashedText(string.Join("@", salt, result.ProviderUserId, result.Provider)), IdProviderName = result.Provider, // terrible hack... Name = result.Provider != "github" ? result.UserName : result.ExtraData["login"] }; using (var db = new QuizWebApp.Models.QuizWebAppDb()) { if (db.Users.Find(user.UserId) == null) { db.Users.Add(user); db.SaveChanges(); } } var cookie = FormsAuthentication.GetAuthCookie(user.Name, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); ticket.GetType().InvokeMember("_UserData", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance, null, ticket, new object[] { user.UserId }); cookie.Value = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(cookie); }
public ActionResult SignIn(SignInViewModel model) { if (!ModelState.IsValid) { return View(model); } var salt = ConfigurationManager.AppSettings["SaltOfUserID"]; var user = new User { Name = model.HandleName, UserId = GetHashedText(string.Join("@", salt, model.HandleName.ToUpperInvariant())), Pass = GetHashedText(string.Join(";", salt, model.HandleName.ToUpperInvariant(), salt, model.Pass)), CreatedAt = DateTime.UtcNow, IsAdmin = false, }; using (var db = new QuizWebAppDb()) { var existing = db.Users.Find(user.UserId); if (existing == null) { if (!db.Users.Any()) { user.IsAdmin = true; } db.Users.Add(user); db.SaveChanges(); } else if (existing.Pass != user.Pass) { ModelState.AddModelError("HandleName", "User already in use with other password"); return View(model); } } var cookie = FormsAuthentication.GetAuthCookie(user.Name, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); ticket.GetType().InvokeMember("_UserData", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance, null, ticket, new object[] { user.UserId }); cookie.Value = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(cookie); return Redirect("~/"); }