protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var identity = HttpContext.Current.User.Identity;

            using (BugTrackerEntities _db = new BugTrackerEntities())
            {
                if (identity.IsAuthenticated)
                {
                    var userManager = actionContext.Request
                                      .GetOwinContext().GetUserManager <ApplicationUserManager>();

                    var user = userManager.FindById(identity.GetUserId());

                    if (!user.EmailConfirmed)
                    {
                        return(false);
                    }
                    else
                    {
                        var appUser = _db.Users.Where(a => a.Id == user.UserId).First();

                        if (appUser.IsDeleted)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(base.IsAuthorized(actionContext));
        }
Example #2
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && db != null)
            {
                db.Dispose();
                db = null;
            }

            base.Dispose(disposing);
        }
Example #3
0
        // Extension method to easily get the count of the tickets a dev is working on.
        // used for badges.
        public static int MyWorkingTicketCount(this System.Security.Principal.IPrincipal user)
        {
            using (var db = new BugTrackerEntities())
            {
                int userID    = user.GetID();
                int myTickets = db.Tickets.Count(t => t.AssignedToID == userID);

                return(myTickets);
            }
        }
        // returns the number of Notifications not read yet.
        public static string NotifyBadgeCount(this System.Security.Principal.IPrincipal user)
        {
            using (var db = new BugTrackerEntities())
            {
                int    userId = user.GetID();
                string count  = db.Notifications
                                .Count(n => n.ToID == userId && n.BeenRead == false)
                                .ToString();

                // add a "+" if it's greater than 1.s
                string badge = (count != "0") ? "+" + count : count;

                return(badge);
            }
        }
        private async Task <bool> SetUpUserRoles(BugTrackerEntities context)
        {
            var roles = context.AspNetRoles.ToList();

            var rSuperAdmin = roles.Where(a => a.Name == this._roleSuperAdmin).FirstOrDefault();
            var rAdmin      = roles.Where(a => a.Name == this._roleAdmin).FirstOrDefault();
            var rUser       = roles.Where(a => a.Name == this._roleUser).FirstOrDefault();

            // Setup super admin role
            if (rSuperAdmin == null)
            {
                context.AspNetRoles.Add(new AspNetRole()
                {
                    Id   = Guid.NewGuid().ToString(),
                    Name = this._roleSuperAdmin
                });
            }

            // Setup admin role
            if (rAdmin == null)
            {
                context.AspNetRoles.Add(new AspNetRole()
                {
                    Id   = Guid.NewGuid().ToString(),
                    Name = this._roleAdmin
                });
            }

            // Setup user role
            if (rUser == null)
            {
                context.AspNetRoles.Add(new AspNetRole()
                {
                    Id   = Guid.NewGuid().ToString(),
                    Name = this._roleUser
                });
            }

            await context.SaveChangesAsync();

            return(true);
        }
Example #6
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Save new user to the user table
                    var db = new BugTrackerEntities();

                    db.Users.Add(new User
                    {
                        ASPUserName = model.UserName,
                        Email       = model.Email,
                        FirstName   = model.FirstName,
                        LastName    = model.LastName
                    });

                    db.SaveChanges();

                    // --- Original Code ---
                    //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            else
            {
                var DB = new BugTrackerEntities();

                var appUser = DB.Users.Where(a => a.Id == user.UserId).FirstOrDefault();

                if (appUser != null && appUser.IsDeleted)
                {
                    context.SetError("invalid_grant", "This account is removed or has no access to the system.");
                    return;
                }
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName, user.UserId);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #8
0
        protected void Seed(ApplicationDbContext context)
        {
            // make Mangers for Roles and User stuff
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            // action to help Create Roles
            Action <string> SeedRole = role =>
            {
                if (!roleManager.RoleExists(role))
                {
                    roleManager.Create(new IdentityRole(role));
                }
            };



            // Create Roles
            SeedRole("Administrator");
            SeedRole("Developer");
            //SeedRole("default");


            // function to easily and safely seed users.
            Action <string, string, string, string> SeedUser = (name, role, email, pass) =>
            {
                // find the user.
                var user = userManager.FindByName(name);

                // if no user then make it.
                if (user == null)
                {
                    // create user
                    user = new ApplicationUser {
                        UserName = name, Email = email
                    };
                    var result = userManager.Create(user, pass);
                }

                // if user isn't in the given role(if a role is given at all), add him.
                if (role != "" && !userManager.IsInRole(user.Id, role))
                {
                    userManager.AddToRole(user.Id, role);
                }


                // --- now add them to user table if they arn't there ---
                var db      = new BugTrackerEntities();
                var bugUser = db.Users.SingleOrDefault(u => u.ASPUserName == user.UserName);

                if (bugUser == null)
                {
                    db.Users.Add(new User
                    {
                        ASPUserName = user.UserName,
                        Email       = user.Email,
                        FirstName   = user.UserName + "First",
                        LastName    = user.UserName + "Last"
                    });

                    db.SaveChanges();
                }
            };


            // seed an admin, developer and some users
            SeedUser("AdminUser", "Administrator", "*****@*****.**", "Password");
            SeedUser("DevUser1", "Developer", "*****@*****.**", "Password");
            SeedUser("DevUser2", "Developer", "*****@*****.**", "Password");
            SeedUser("User1", "", "*****@*****.**", "Password");
            SeedUser("User2", "", "*****@*****.**", "Password");
            SeedUser("User3", "", "*****@*****.**", "Password");
        }
Example #9
0
        // Main function to set up
        public static void UpdateTicketAndLog(Ticket newTicket, int editorID)
        {
            // it's BETTER to create a NEW instance of the db than to use an old copy that.
            // for example: if the 'NewTicket' was first retrieved from the db, and then passed in here, if I had used the same
            // db context to grab the 'OldTicket' it would really be grabing my modified new ticket.s
            using (var db = new BugTrackerEntities())
            {
                // Ticket Should already be valid by the time it reaches here.
                // get the original ticket and store it.
                Ticket oldTicket = db.Tickets.AsNoTracking()
                                   .Include(t => t.Project)
                                   .Include(t => t.TicketPriority)
                                   .Include(t => t.TicketStatus)
                                   .Include(t => t.TicketType)
                                   .Include(t => t.User1) // dev.
                                   .Single(t => t.ID == newTicket.ID);


                // Save the New Ticket
                db.Entry(newTicket).State = EntityState.Modified;

                db.SaveChanges();


                //load the new ticket with all of it's potentially new props.
                newTicket = db.Tickets
                            .Include(t => t.Project)
                            .Include(t => t.TicketPriority)
                            .Include(t => t.TicketStatus)
                            .Include(t => t.TicketType)
                            .Include(t => t.User1)      // dev.
                            .Single(t => t.ID == newTicket.ID);

                // create History log variable
                string historyInnerHTML = null;

                // LONG list of checks.
                // so we are using the id's that are in the ticket BECAUSE if the id isn't there, the property won't be there,
                // and things get ugly when the property is not there!

                // b/c developer can be null, we need to go over all possible cases.
                if (oldTicket.AssignedToID != newTicket.AssignedToID)
                {
                    if (oldTicket.AssignedToID == null)
                    {
                        historyInnerHTML += HistoryMessage("Developer", "Unassigned", newTicket.User1.ASPUserName);
                    }

                    else if (newTicket.AssignedToID == null)
                    {
                        historyInnerHTML += HistoryMessage("Developer", oldTicket.User1.ASPUserName, "Unassigned");
                    }

                    else
                    {
                        historyInnerHTML += HistoryMessage("Developer", oldTicket.User1.ASPUserName, newTicket.User1.ASPUserName);
                    }
                }

                if (oldTicket.ProjectID != newTicket.ProjectID)
                {
                    historyInnerHTML += HistoryMessage("Project", oldTicket.Project.ProjectName, newTicket.Project.ProjectName);
                }

                if (oldTicket.TicketPriorityID != newTicket.TicketPriorityID)
                {
                    historyInnerHTML += HistoryMessage("Priority", oldTicket.TicketPriority.Priority, newTicket.TicketPriority.Priority);
                }

                if (oldTicket.TicketStatusID != newTicket.TicketStatusID)
                {
                    historyInnerHTML += HistoryMessage("Ticket Status", oldTicket.TicketStatus.Status, newTicket.TicketStatus.Status);
                }

                if (oldTicket.TicketTypeID != newTicket.TicketTypeID)
                {
                    historyInnerHTML += HistoryMessage("Ticket Type", oldTicket.TicketType.Type, newTicket.TicketType.Type);
                }

                if (oldTicket.Title != newTicket.Title)
                {
                    historyInnerHTML += HistoryMessage("Title", oldTicket.Title, newTicket.Title);
                }

                if (oldTicket.Description != newTicket.Description)
                {
                    historyInnerHTML += HistoryMessage("Description", oldTicket.Description, newTicket.Description);
                }

                // b/c resolution can be null, check for all cases.
                if (oldTicket.Resolution != newTicket.Resolution)
                {
                    if (oldTicket.Resolution == null || oldTicket.Resolution == "")
                    {
                        historyInnerHTML += HistoryMessage("Resolution", "Unresolved", newTicket.Resolution);
                    }

                    else
                    {
                        historyInnerHTML += HistoryMessage("Resolution", oldTicket.Resolution, newTicket.Resolution);
                    }
                }


                // should catch the case that nothing is updated.
                if (historyInnerHTML == null)
                {
                    return;
                }


                // create and save the history.
                db.TicketHistories.Add(new TicketHistory
                {
                    TicketID          = newTicket.ID,
                    DateOfChange      = DateTime.UtcNow,
                    TicketEditorID    = editorID,
                    Ticket_Alteration = historyInnerHTML
                });

                db.SaveChanges();
            }
        }