Example #1
0
        GetBaseNoteHeadersForFile(int id)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(new List <NoteHeader>());
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager
                                .GetAccess(_context, userID, id, 0);

            if (!myAcc.ReadAccess)
            {
                return(new List <NoteHeader>());
            }

            List <NoteHeader> stuff = await NoteDataManager
                                      .GetBaseNoteHeaders(_context, id, 0);

            return(stuff);
        }
Example #2
0
        public async Task <ActionResult <IEnumerable <NoteFile> > > GetFileList()
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(new List <NoteFile>());
            }

            List <NoteFile> allFiles = await NoteDataManager
                                       .GetNoteFilesOrderedByName(_context);

            List <NoteFile> myFiles = new List <NoteFile>();

            foreach (var file in allFiles)
            {
                file.Owner = null;
                NoteAccess myAccess = await AccessManager
                                      .GetAccess(_context, me.Id, file.Id, 0);

                if (myAccess.ReadAccess || myAccess.Write)
                {
                    myFiles.Add(file);
                }
            }

            return(myFiles);
        }
Example #3
0
        GetNoteContent(int id, int id2, int id3)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager
                                 .FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(new NoteContent());
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager.GetAccess(_context, userID, id, 0);

            if (!myAcc.ReadAccess)
            {
                return(new NoteContent());
            }

            NoteContent result = await NoteDataManager
                                 .GetNoteContent(_context, id, 0, id2, id3);

            return(result);
        }
Example #4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    IdentityUser me = await _userManager.FindByNameAsync(Input.Email);

                    string uId = await _userManager.GetUserIdAsync(me);

                    UserAuxData aux = new UserAuxData();
                    aux.UserId      = uId;
                    aux.DisplayName = Input.DisplayName;
                    aux.TimeZoneID  = Globals.TimeZoneDefaultID;

                    _db.UserData.Add(aux);
                    await _db.SaveChangesAsync();

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
        public async Task <NoteHeader> Create(TextViewModel inputModel)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(null);
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager.
                                GetAccess(_context, userID, inputModel.NoteFileID, 0);

            if (!myAcc.Write)
            {
                return(null);
            }

            await _signInManager.SignInAsync(me, false);

            DateTime now = DateTime.Now.ToUniversalTime();

            NoteHeader nheader = new NoteHeader()
            {
                LastEdited       = now,
                ThreadLastEdited = now,
                CreateDate       = now,
                NoteFileId       = inputModel.NoteFileID,
                AuthorName       = appMe.DisplayName,
                AuthorID         = _userManager.GetUserId(User),
                NoteSubject      = inputModel.MySubject,
                ResponseOrdinal  = 0,
                ResponseCount    = 0
            };

            if (inputModel.BaseNoteHeaderID == 0)
            {
                return(await NoteDataManager
                       .CreateNote(_context, _userManager, nheader,
                                   inputModel.MyNote.Replace("\n", "<br />"),
                                   inputModel.TagLine,
                                   inputModel.DirectorMessage, true, false));
            }
            NoteHeader bnh = await NoteDataManager.GetNoteHeader(_context, inputModel.BaseNoteHeaderID);

            nheader.BaseNoteId = bnh.Id;
            return(await NoteDataManager.CreateResponse(_context, _userManager,
                                                        nheader, inputModel.MyNote, inputModel.TagLine,
                                                        inputModel.DirectorMessage, true, false));
        }
Example #6
0
        public async Task <IActionResult> Preferences()
        {
            UserAuxData user = await _db.UserData.SingleAsync(p => p.UserId == _userManager.GetUserId(User));

            TextReader sr = new StreamReader(_stylePath);

            ViewBag.DefaultStyle = await sr.ReadToEndAsync();

            sr.Close();

            return(View(user));
        }
Example #7
0
        public async Task <IActionResult> SetTimeZone(TimeZoneModel model)
        {
            UserAuxData user = await _db.UserData.SingleAsync(p => p.UserId == _userManager.GetUserId(User));

            user.TimeZoneID       = model.TimeZoneID;
            _db.Entry(user).State = EntityState.Modified;
            await _db.SaveChangesAsync();

            HttpContext.Session.Remove("TZone");

            return(RedirectToAction("Index"));
        }
Example #8
0
        public static UserAuxData GetUserAuxData(UserManager <IdentityUser> userManager, ClaimsPrincipal user, ApplicationDbContext db)
        {
            UserAuxData aux = null;

            try
            {
                string userid = userManager.GetUserId(user);
                aux = db.UserData.SingleOrDefault(p => p.UserId == userid);
            }
            catch
            { }
            return(aux);
        }
Example #9
0
        public async Task <IActionResult> Preferences(UserAuxData model)
        {
            UserAuxData user = await _db.UserData.SingleAsync(p => p.UserId == _userManager.GetUserId(User));

            user.Pref1   = model.Pref1;
            user.Pref2   = model.Pref2;
            user.MyStyle = model.MyStyle;

            _db.Entry(user).State = EntityState.Modified;
            await _db.SaveChangesAsync();

            HttpContext.Session.Remove("MyStyle");

            return(RedirectToAction("Index"));
        }
Example #10
0
        private static async Task SendNewNoteToSubscribers(ApplicationDbContext db, UserManager <IdentityUser> userManager, NoteHeader nc)
        {
            nc.NoteFile.NoteHeaders = null;
            ForwardViewModel fv = new ForwardViewModel()
            {
                NoteSubject = "New Note from Notes 2021"
            };
            List <Subscription> subs = await db.Subscription
                                       .Where(p => p.NoteFileId == nc.NoteFileId)
                                       .ToListAsync();

            List <string> emails = new List <string>();

            fv.ToEmail     = "xx";
            fv.FileID      = nc.NoteFileId;
            fv.hasstring   = false;
            fv.NoteID      = nc.Id;
            fv.NoteOrdinal = nc.NoteOrdinal;
            fv.NoteSubject = nc.NoteSubject;
            fv.toAllUsers  = false;
            fv.IsAdmin     = false;
            fv.wholestring = false;


            foreach (Subscription s in subs)
            {
                UserAuxData usr = await db.UserData.SingleAsync(p => p.UserId == s.SubscriberId);

                NoteAccess myAccess = await AccessManager.GetAccess(db, usr.UserId, nc.NoteFileId, 0);

                if (myAccess.ReadAccess)
                {
                    emails.Add((await userManager.FindByIdAsync(usr.UserId)).Email);
                }
            }

            if (emails.Count > 0)
            {
                string payload = await MakeNoteForEmail(fv, db, "BackgroundJob", "Notes 2021");

                foreach (string em in emails)
                {
                    await Globals.EmailSender.SendEmailAsync(em, fv.NoteSubject, payload);
                }

                //await Globals.EmailSender.SendEmailListAsync(emails, fv.NoteSubject, payload);
            }
        }
Example #11
0
        public static string GetUserDisplayName(UserManager <IdentityUser> userManager, ClaimsPrincipal user, ApplicationDbContext db)
        {
            UserAuxData aux    = null;
            string      myName = " ";

            try
            {
                string userid = userManager.GetUserId(user);
                aux    = db.UserData.SingleOrDefault(p => p.UserId == userid);
                myName = aux.DisplayName;
            }
            catch
            { }

            return(myName);
        }
        public async Task <NoteHeader> Edit(TextViewModel inputModel)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(null);
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager.GetAccess(_context, userID, inputModel.NoteFileID, 0); //TODO

            if (!myAcc.Write)
            {
                return(null);
            }

            await _signInManager.SignInAsync(me, false);

            DateTime now = DateTime.Now.ToUniversalTime();

            NoteHeader oheader = await NoteDataManager
                                 .GetBaseNoteHeaderById(_context, inputModel.NoteID);

            if (oheader.AuthorID != userID) // must be a note this user wrote.
            {
                return(null);
            }

            oheader.LastEdited       = now;
            oheader.ThreadLastEdited = now;
            oheader.NoteSubject      = inputModel.MySubject;

            NoteContent oContent = await NoteDataManager
                                   .GetNoteContent(_context, oheader.NoteFileId, 0, oheader.NoteOrdinal, oheader.ResponseOrdinal); //TODO

            oContent.NoteBody        = inputModel.MyNote;
            oContent.DirectorMessage = inputModel.DirectorMessage;

            return(await NoteDataManager
                   .EditNote(_context, _userManager, oheader, oContent, inputModel.TagLine));
        }
        public async Task <MemoryStream> GetFileAs(int id, bool id2)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(null);
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager.GetAccess(_context, userID, id, 0); //TODO

            if (!myAcc.ReadAccess)
            {
                return(null);
            }

            ExportController myExp = new ExportController(_appEnv,
                                                          _userManager, _signInManager, _context);
            ExportViewModel model = new ExportViewModel();

            NoteFile nf = await NoteDataManager.GetFileById(_context, id);

            model.NoteOrdinal   = 0;
            model.FileName      = nf.NoteFileName;
            model.FileNum       = nf.Id;
            model.directOutput  = true;
            model.isCollapsible = id2;
            model.isHtml        = id2;

            IdentityUser applicationUser = await _userManager
                                           .FindByEmailAsync(auths[0]);

            await _signInManager.SignInAsync(applicationUser, false);

            model.tzone = _context.TZones.Single(p => p.Id == appMe.TimeZoneID);

            return(await myExp.DoExport(model, User, 0));   //TODO
        }
Example #14
0
        public async Task <ActionResult <NoteAccess> > GetAccess(int id)
        {
            string authHeader = Request.Headers["authentication"];

            string[] auths = authHeader.Split(',');

            IdentityUser me = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return(new NoteAccess());
            }
            string     userID = auths[1];
            NoteAccess myAcc  = await AccessManager.GetAccess(_context, userID, id, 0);

            return(myAcc);
        }
Example #15
0
        public async Task <string> Login()
        {
            long?lth = Request.ContentLength;

            var str = Request.Body;

            byte[] by = new byte[200];
            if (lth != null)
            {
                try
                {
                    await str.ReadAsync(by, 0, (int)lth);
                }
                catch (Exception ex)
                {
                    string x = ex.Message;
                }
                string converted = Encoding.UTF8.GetString(by, 0, (int)lth);

                string[] items  = converted.Split('/');
                var      result = await _signInManager.PasswordSignInAsync(items[0], items[1], false, true);

                if (result.Succeeded)
                {
                    IdentityUser me = await _userManager.FindByEmailAsync(items[0]);

                    UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

                    if (string.IsNullOrEmpty(appMe.MyGuid))
                    {
                        string myGuid = Guid.NewGuid().ToString();
                        appMe.MyGuid = myGuid;
                        await _userManager.UpdateAsync(me);
                    }

                    string mykey = items[0] + "," + me.Id + "," + appMe.MyGuid;

                    return(mykey);
                }
            }

            return(null);    // tell client login failed
        }
Example #16
0
        public async Task <IActionResult> SetTimeZone()
        {
            TimeZoneModel model = new TimeZoneModel();
            UserAuxData   user  = await _db.UserData.SingleAsync(p => p.UserId == _userManager.GetUserId(User));

            model.TimeZoneID = user.TimeZoneID;
            if (model.TimeZoneID < 1)
            {
                model.TimeZoneID = Globals.TimeZoneDefaultID;
            }

            List <TZone> tzones = await _db.TZones
                                  .OrderBy(p => p.OffsetHours)
                                  .ThenBy(p => p.OffsetMinutes)
                                  .ThenBy(p => p.Name)
                                  .ToListAsync();

            model.timeZone = await _db.TZones.SingleAsync(p => p.Id == model.TimeZoneID);

            List <SelectListItem> list2 = new List <SelectListItem>
            {
                new SelectListItem
                {
                    Value = "0",
                    Text  = "-- Select a Time Zone --"
                }
            };

            foreach (TZone t in tzones)
            {
                list2.Add(new SelectListItem
                {
                    Selected = t.Id == model.TimeZoneID,
                    Value    = "" + t.Id,
                    Text     = t.Offset + " - " + t.Name
                });
            }

            ViewBag.OptionList = list2;

            return(View(model));
        }
Example #17
0
        public async Task DeleteNote(long id)
        {
            string authHeader = Request.Headers["authentication"];

            string[]     auths = authHeader.Split(',');
            IdentityUser me    = await _userManager.FindByIdAsync(auths[1]);

            UserAuxData appMe = await _context.UserData.SingleAsync(p => p.UserId == me.Id);

            if (String.Compare(auths[2], appMe.MyGuid, StringComparison.Ordinal) != 0)
            {
                return;
            }

            NoteHeader myNote = await NoteDataManager.GetNoteById(_context, id);

            if (myNote.AuthorID != auths[1])  // user must be the Author
            {
                return;
            }

            await NoteDataManager.DeleteNote(_context, myNote);
        }
Example #18
0
        public async Task <IActionResult> Index()
        {
            if (!_roleManager.Roles.Any())
            {
                await _roleManager.CreateAsync(new IdentityRole { Name = "User" });

                await _roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
            }

            TZone tzone = await LocalManager.GetUserTimeZone(HttpContext, User, _userManager, _signInManager, _db);

            HomePageModel myModel = new HomePageModel
            {
                Tzone       = tzone,
                UpdateClock = false
            };


beyond:

            if (_signInManager.IsSignedIn(User))
            {
                IdentityUser usr;
                try
                {
                    usr = await _userManager.GetUserAsync(User);
                }
                catch
                {
                    await _signInManager.SignOutAsync();

                    goto beyond;
                }

                if (!User.IsInRole("User"))
                {
                    await _userManager.AddToRoleAsync(usr, "User");
                }

                if (_userManager.Users.Count() == 1 && !User.IsInRole("Admin"))
                {
                    // Only/First user - Make an Admin!
                    await _userManager.AddToRoleAsync(usr, "Admin");
                }

                UserAuxData aux = NoteDataManager.GetUserAuxData(_userManager, User, _db);
                HttpContext.Session.SetInt32("HideNoteMenu", Convert.ToInt32(aux.Pref1));
                HttpContext.Session.SetInt32("ArchiveID", Convert.ToInt32(0));
                string uName = NoteDataManager.GetSafeUserDisplayName(_userManager, User, _db);

                //Jobs job = new Jobs();
                //if (user.Pref2)
                //{
                //    myModel.UpdateClock = true;
                //    RecurringJob.AddOrUpdate(uName, () => job.UpdateHomePageTime(uName, tzone), Cron.Minutely);
                //    RecurringJob.AddOrUpdate("delete_" + uName, () => job.CleanupHomePageTime(uName), Cron.Daily);
                //}
                //else
                //{
                //    RecurringJob.RemoveIfExists(uName);
                //}

                HttpContext.Session.SetInt32("IsSearch", 0);    // clear the searching flag
                try
                {
                    // if this user has a searchView row in the DB, delete it

                    Search searchView = await NoteDataManager.GetUserSearch(_db, aux.UserId);

                    if (searchView != null)
                    {
                        _db.Search.Remove(searchView);
                        await _db.SaveChangesAsync();
                    }
                }
                catch
                {
                    // if we cannot talk to the DB, route the user to the setup directions
                    //return RedirectToAction("SetUp");
                }

                //Direct link to 3 important files

                myModel.IFiles = await _db.NoteFile
                                 .Where(p => p.NoteFileName == "announce" || p.NoteFileName == "pbnotes" || p.NoteFileName == "noteshelp")
                                 .OrderBy(p => p.NoteFileName)
                                 .ToListAsync();

                // History files

                myModel.HFiles = await _db.NoteFile
                                 .Where(p => p.NoteFileName == "Gnotes" || p.NoteFileName == "Opbnotes")
                                 .OrderBy(p => p.NoteFileName)
                                 .ToListAsync();

                // Get a list of all file names for dropdown
                IEnumerable <SelectListItem> items = LocalManager.GetFileNameSelectList(_db);
                List <SelectListItem>        list2 = new List <SelectListItem>();
                list2.AddRange(items);

                myModel.AFiles = list2;

                // Get a list of all file titles for dropdown
                items = LocalManager.GetFileTitleSelectList(_db);
                list2 = new List <SelectListItem>();
                list2.AddRange(items);
                myModel.ATitles = list2;

                HomePageMessage mess = await _db.HomePageMessage.OrderByDescending(p => p.Id).FirstOrDefaultAsync();

                myModel.Message = mess != null ? mess.Message : "";
            }

            ViewData["MyName"] = NoteDataManager.GetUserDisplayName(_userManager, User, _db);
            return(View(_userManager, myModel));
        }