public static void CheckUser(this Controller c) { string userid = null; if (c.Request.IsAuthenticated) { userid = c.User.Identity.GetUserName(); c.ViewBag.UserName = userid; var isAdmin = false; if (c.Session["IsAdmin"] == null) { isAdmin = c.GetUserManager().IsInRole(c.User.Identity.GetUserId(), "admin"); c.Session["IsAdmin"] = isAdmin; } else { isAdmin = (bool)c.Session["IsAdmin"]; } c.ViewBag.IsAdmin = isAdmin; // get the firebase API key try { var key = c.Session["apikey"]; if (key == null) { var context = c.HttpContext.GetOwinContext(); var db = context.Get <ApplicationDbContext>(); var table = db.Config; SharedAppConfig config = table.Find("ApiKey"); if (config != null) { key = config.Value; c.Session["apikey"] = key; } } c.ViewBag.ApiKey = key; } catch (Exception) { // hmmm, the table is still missing... } } else { c.ViewBag.IsAdmin = false; c.ViewBag.UserName = ""; } }
public async Task <ActionResult> SetKey(SetKeyModel model) { this.CheckUser(); if (ModelState.IsValid) { if (!ViewBag.IsAdmin) { ModelState.AddModelError("", "Sorry, you do not have permission to change the firebase key"); } else { try { var context = this.HttpContext.GetOwinContext(); var db = context.Get <ApplicationDbContext>(); var table = db.Config; SharedAppConfig config = await table.FindAsync("ApiKey"); if (config == null) { config = new SharedAppConfig() { Id = "ApiKey", Value = model.ApiKey }; table.Add(config); } else { config.Value = model.ApiKey; } await db.SaveChangesAsync(); model.Result = "updated"; } catch (Exception ex) { model.Result = ex.Message; } } } // If we got this far, something failed, redisplay form return(View(model)); }