public SimpleMembershipInitializer() { Database.SetInitializer<UsersContext>(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { // Create the SimpleMembership database without Entity Framework migration schema ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex); } }
Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync() { return Task.Factory.StartNew<RefreshTokenInfo>(() => { RefreshTokenInfo token = null; using (UsersContext db = new UsersContext()) { MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name); if (msAccount != null) { token = new RefreshTokenInfo(msAccount.RefreshToken, msAccount.MSUserId); this.msAccountStatus = MSAccountStatus.Connected; } } return token; }); }
Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo) { this.msAccountStatus = MSAccountStatus.Connected; return Task.Factory.StartNew(() => { using (UsersContext db = new UsersContext()) { MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name); if (msAccount != null) { if (tokenInfo.UserId != msAccount.MSUserId) { throw new LiveAuthException("invalid_user", "The account Id from the ticket does not match the current connected user."); } msAccount.RefreshToken = tokenInfo.RefreshToken; db.Entry(msAccount).State = System.Data.EntityState.Modified; } else { // Insert name into the profile table db.MSAccounts.Add(new MSAccount { MSUserId = tokenInfo.UserId, RefreshToken = tokenInfo.RefreshToken, UserName = this.User.Identity.Name }); } db.SaveChanges(); } }); }
public ActionResult DisconnectMicrosoft() { if (this.MSAccountStatus != Controllers.MSAccountStatus.NotConnected) { // Remove the account association using (UsersContext db = new UsersContext()) { MSAccount msAccount = db.MSAccounts.FirstOrDefault(u => u.UserName == this.User.Identity.Name); if (msAccount != null) { db.MSAccounts.Remove(msAccount); db.SaveChanges(); } } this.msAccountStatus = MSAccountStatus.NotConnected; } this.MSAuthClient.ClearSession(this.HttpContext); this.Response.Redirect(this.SiteRootPath + "account/connectmicrosoft"); return null; }