Exemple #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                cProject = projectContext.GetById(int.Parse(Request.Params.Get("project")));

                Page.Title           = "Project: " + cProject.Name;
                LB_Owner.Text        = userContext.GetUsername(cProject.OwnerId);
                LB_Desc.Text         = cProject.Description;
                Uploadfile1.id       = cProject.IdProject;
                Uploadfile1.fileType = FileType.Project;
            }
            catch (Exception)
            {
                Response.Redirect("/Errors/403.aspx");
            }

            //Uploadfile1.Visible = Context.User.IsInRole(UserType.Teacher.ToString());

            var context = new IdentityDb();

            //Uploadfile1.Visible = context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Prof.ToString();

            if (cProject == null)
            {
                Response.Redirect("/Errors/403.aspx");
            }
            // else

            showFileList();

            // check if owner for edit button
            Button_Update.Visible = Context.User.Identity.GetUserId() == cProject.OwnerId;
        }
        public async Task <ActionResult> SupplierRegis([Bind(Include = "suppliersave_SupplierID,suppliersave_SupplierName,suppliersave_Notes")] RegisterSupplier model)
        {
            using (var context = new IdentityDb())
            {
                if (ModelState.IsValid)
                {
                    var roleStore   = new RoleStore <IdentityRole>(context);
                    var roleManager = new RoleManager <IdentityRole>(roleStore);

                    var user = new ApplicationUser {
                        UserName = model.registsupplier.Username, SupplierName = model.registsupplier.SupplierName
                    };
                    var result = await UserManager.CreateAsync(user, model.registsupplier.Password);

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        await UserManager.FindAsync(model.registsupplier.Username, model.registsupplier.Password);

                        await this.UserManager.AddToRoleAsync(user.Id, "supplier");
                    }

                    db.Suppliers.Add(model.suppliersave);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            return(View());
        }
        /*
         * ATTENTION :
         *
         *          SI VOUS VOULEZ REDIRIGER VERS UNE PAGE
         *          UTILISEZ RESPONSE.REDIRECT  (Et non pas Server.transfer)
         *          C EST PRIMORDIAL POUR LE MECANISME DE "POSTBACK"
         *
         *          JE VOUS INVITE FORTEMENT A ALLER VOIR : https://docs.microsoft.com/en-us/previous-versions/ms178472(v=vs.140)
         *          (déso pour le caps lock, mais c est important,
         *          j'ai passé 2h à essayer de comprendre un pb qui n'existait pas)
         * * * * * * * * * * * * * * * * * * * * * * * * * */
        protected void Page_Load(object sender, EventArgs e)
        {
            var context = new IdentityDb();

            Quizz.Visible      = context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Prof.ToString();
            AddStudent.Visible = context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Prof.ToString();
        }
Exemple #4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            cUV = uvContext.GetByDenomination(Request.Params.Get("uv"));

            var context = new IdentityDb();

            Uploadfile1.Visible = context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Prof.ToString();

            if (cUV == null)
            {
                Response.Redirect("/Errors/403.aspx");
            }
            // else

            Page.Title           = cUV.Denomination + ": " + cUV.Name;
            LB_Owner.Text        = userContext.GetUsername(cUV.Owner);
            LB_Desc.Text         = cUV.Description;
            Uploadfile1.id       = cUV.IdUv;
            Uploadfile1.fileType = FileType.UV;

            showFileList();
            ShowQuizzesList();
            ShowProjectList();

            // check if owner for edit button
            bool isOwner = Context.User.Identity.GetUserId() == cUV.Owner;

            Button_Update_UV.Visible   = isOwner;
            Button_AddQuizz.Visible    = isOwner;
            Button_Add_Project.Visible = isOwner;
            Button_Add_Teacher.Visible = isOwner;
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            // Le code ci-dessous vous aide à vous protéger des attaques XSRF
            var context = new IdentityDb();

            AdministrationPanel.Visible = context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Admin.ToString();
            var  requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;

            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Utiliser le jeton Anti-XSRF à partir du cookie
                _antiXsrfTokenValue   = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Générer un nouveau jeton Anti-XSRF et l'enregistrer dans le cookie
                _antiXsrfTokenValue   = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value    = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }
Exemple #6
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            IdentityDb db      = context.Get <IdentityDb>();
            var        manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <IdentityDb>()));

            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = true,
                RequireLowercase        = false,
                RequireUppercase        = false
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(1);
            manager.MaxFailedAccessAttemptsBeforeLockout = 2;

            //var dataProtectionProvider = options.DataProtectionProvider;
            //if (dataProtectionProvider != null)
            //{
            //    manager.UserTokenProvider =
            //        new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            //}

            return(manager);
        }
Exemple #7
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            using (var context = new IdentityDb())
            {
                var userStore   = new UserStore <IdentityUser>(context);
                var userManager = new UserManager <IdentityUser>(userStore);
                var user        = userManager.Find(tbUserName.Text, tbPassword.Text);

                if (user == null)
                {
                    lblError.Text = "Invalid username or password!";
                    divError.Attributes["class"] = "form-field visible";
                }
                else
                {
                    var authMgr      = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authMgr.SignIn(new AuthenticationProperties()
                    {
                        IsPersistent = false
                    }, userIdentity);
                    using (var appContext = new DotWebDb())
                    {
                        var appUser = appContext.Users.SingleOrDefault(u => u.UserName.Equals(user.UserName, StringComparison.InvariantCultureIgnoreCase));
                        if (appUser != null)
                        {
                            Session["user"] = appUser;
                        }
                    }
                    Response.Redirect("~/");
                }
            }
        }
Exemple #8
0
 static void Main()
 {
     _CycleRepository = new CycleRepository();
     _idb             = new IdentityDb();
     DeleteOldRidesAndCreateNew();
     PopulateHomePageRide();
     CheckUserExpands(_idb);
 }
Exemple #9
0
        public async Task <JsonResult> Edit(UserViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Json(new { Error = "Complete all required fields" }));
                }
                if (string.IsNullOrEmpty(model.Id))
                {
                    //create user
                    var user = Mapper.Map <ApplicationUser>(model);
                    user.Id = Guid.NewGuid().ToString();
                    var randomPassword = GeneratePassword(8);
                    var result         = await UserManager.CreateAsync(user, randomPassword);

                    if (result.Succeeded)
                    {
                        await UserManager.AddToRoleAsync(user.Id, "user");

                        //send email
                        var currentUser = UserManager.Users.SingleOrDefault(item => item.Id == UserId);

                        string msg = GetRegisterUsertEmailMsg();
                        msg = msg.Replace("@username", model.FirstName);
                        msg = msg.Replace("@byusername", currentUser?.FirstName + " " + currentUser?.LastName);
                        msg = msg.Replace("@email", model.Email);
                        msg = msg.Replace("@password", randomPassword);
                        msg = msg.Replace("@loginlink",
                                          ConfigurationManager.AppSettings["SiteAddress"] + "/Account/Login");
                        msg = msg.Replace("@siteaddress", ConfigurationManager.AppSettings["SiteAddress"]);
                        MailService.SendMail(model.Email, "Truck System User Details", msg);
                        return(Json(new { Done = 1 }));
                    }
                    return(Json(new { Error = "Cannot create user, please try again later." }));
                }
                else
                {
                    var user = await IdentityDb.Users.SingleOrDefaultAsync(item => item.Id == model.Id);

                    if (user != null)
                    {
                        user.FirstName   = model.FirstName;
                        user.LastName    = model.LastName;
                        user.CustomerId  = model.CustomerId;
                        user.Email       = model.Email;
                        user.PhoneNumber = model.PhoneNumber;
                        IdentityDb.SaveChanges();
                        return(Json(new { Done = 1 }));
                    }
                    return(Json(new { Error = "User not exist." }));
                }
            }
            catch (Exception exp)
            {
                return(null);
            }
        }
 public IdentityService(UserManager <IdentityUser> userManager, ITokenProvider tokenProvider,
                        IPrincipalProvider principalProvider, JwtSettings jwtSettings, IdentityDb context)
 {
     _userManager       = userManager;
     _tokenProvider     = tokenProvider;
     _principalProvider = principalProvider;
     _jwtSettings       = jwtSettings;
     _context           = context;
 }
Exemple #11
0
        private static void CheckUserExpands(IdentityDb context)
        {
            int Totalusers        = _idb.Users.Count();
            int TotalExpandConfig = _CycleRepository.GetUserExpandCount();

            if (Totalusers != TotalExpandConfig)
            {
                foreach (var item in _idb.Users)
                {
                    _CycleRepository.PopulateInitialExpandValues(item.Id.ToString());
                }
            }
        }
Exemple #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var context = new IdentityDb();

            if (!(context.GetUserRole(Context.User.Identity.GetUserId()) == CustomRoles.roles.Prof.ToString()))
            {
                Button2.Visible = false;
            }
            else
            {
                Button2.Visible = true;
            }
        }
Exemple #13
0
        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            try
            {
                using (var context = new IdentityDb())
                {
                    var userStore   = new UserStore <IdentityUser>(context);
                    var userManager = new UserManager <IdentityUser>(userStore);

                    var user = new IdentityUser()
                    {
                        UserName = tbUserName.Text, Email = tbEmail.Text
                    };
                    IdentityResult result = userManager.Create(user, tbPassword.Text);

                    if (result.Succeeded)
                    {
                        using (var appContext = new DotWebDb())
                        {
                            var appUser = new User()
                            {
                                Id             = user.Id,
                                UserName       = user.UserName,
                                Email          = user.Email,
                                FirstName      = tbFirstName.Text,
                                LastName       = tbLastName.Text,
                                OrganizationId = cbOrganization.SelectedItem == null ? null : (int?)int.Parse(cbOrganization.SelectedItem.Value.ToString())
                            };
                            appContext.Users.Add(appUser);
                            appContext.SaveChanges();
                        }

                        Response.Redirect(Request.QueryString["ReturnUrl"] ?? "~/Admin/Users.aspx");
                    }
                    else
                    {
                        lblError.Text = "";
                        foreach (var error in result.Errors)
                        {
                            lblError.Text += error;
                        }
                        divError.Attributes["class"] = "form-field visible";
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                divError.Attributes["class"] = "form-field visible";
            }
        }
Exemple #14
0
        public ActionResult RoleCreate(string roleName)
        {
            using (var context = new IdentityDb())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                roleManager.Create(new IdentityRole(roleName));
                context.SaveChanges();
            }

            ViewBag.ResultMessage = "Role created successfully !";
            return(RedirectToAction("RoleIndex", "Account"));
        }
Exemple #15
0
        public ActionResult RoleIndex()
        {
            List <string> roles;

            using (var context = new IdentityDb())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                roles = (from r in roleManager.Roles select r.Name).ToList();
            }

            return(View(roles.ToList()));
        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            IdentityDb context = new IdentityDb();
            var        store   = new UserStore <ApplicationUser>(context);
            var        manager = new UserManager <ApplicationUser>(store);

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var userId = HttpContext.Current.User.Identity.GetUserId();
                filterContext.Controller.ViewBag.UserRoles = manager.GetRoles(userId);

                ApplicationUser user = manager.FindById(userId);
                filterContext.Controller.ViewBag.UserInfo = user;
            }
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(IdentityDb.Create()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
 private static void AddCurrencies(this IdentityDb db)
 {
     if (!db.Currencies.Any())
     {
         db.Currencies.AddRange(new Currency()
         {
             Name = "RM"
         },
                                new Currency()
         {
             Name = "IRR"
         }
                                );
         db.SaveChanges();
     }
 }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            List <IdentityRole> roles;

            if (model.Role != "supplier")
            {
                model.SupplierName = "";
            }
            using (var context = new IdentityDb())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);
                roles = (from r in roleManager.Roles select r).ToList();

                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser {
                        UserName = model.Username, SupplierName = model.SupplierName
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        await UserManager.FindAsync(model.Username, model.Password);

                        await this.UserManager.AddToRoleAsync(user.Id, model.Role);

                        // 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);
                }


                ViewBag.Roles = roles;//new SelectList(roles, "Role", "Role");
                // If we got this far, something failed, redisplay form
                //return PartialView(model);
                return(RedirectToAction("Register", "Account", model));
            }
        }
        public IHttpActionResult GetOrder(int id)
        {
            getOrdersDTO objOrder = new getOrdersDTO();

            var userId = ((ClaimsIdentity)User.Identity).GetUserId();
            var context = new IdentityDb();
            // Orders for Providers
            objOrder = db.Orders
                 .Include(i => i.IngOrders)
                 .Include(c => c.IngOrders.Select(s => s.IngNotiPost))
                 .Where(x => x.OrderId == id)
                 .Select(ordR => new getOrdersDTO
                 {
                     orderId = ordR.OrderId,
                     providerId = ordR.IngOrders.Select(inp => inp.IngNotiPost.ProviderId).FirstOrDefault(),
                     restaurantId = ordR.RestaurantId,
                     createdDate = ordR.CreatedDate,
                     status = ordR.Status,
                     totalcost = ordR.TotalCost
                 }).FirstOrDefault();

            objOrder.providerName = context.Users.Where(x => x.Id == objOrder.providerId).Select(u => u.CompanyName).FirstOrDefault();
            objOrder.restaurantName = context.Users.Where(x => x.Id == objOrder.restaurantId).Select(u => u.CompanyName).FirstOrDefault();

            objOrder.IngOrders = new List<getOrdersDetailDTO>();

                 var listIO = db.IngOrders
                .Include(i=> i.IngNotiPost).Include(o=> o.IngNotiPost.IngNotification.IngDish)
                .Where(i=> i.Order.OrderId == id)
                .Select(ord => new getOrdersDetailDTO() {
                    ingOrderId = ord.IngOrderId,
                    ingName = ord.IngNotiPost.IngNotification.IngDish.Ingredient.Name,
                    totalRequired = ord.IngNotiPost.IngNotification.TotalRequired,
                    unitCost = ord.IngNotiPost.UnitCost,
                    totalReceived = ord.TotalReceived

                }).ToList();

            objOrder.IngOrders = listIO;

            if (objOrder == null)
            {
                return NotFound();
            }

            return Ok(objOrder);
        }
Exemple #21
0
        public ActionResult Register()
        {
            List <string> roles;

            using (var context = new IdentityDb())
            {
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);

                roles = (from u in roleManager.Roles select u.Name).ToList();
            }


            // ViewBag.SupplierName = new SelectList(selectmachine.ToList(), "SupplierName", "text");
            ViewBag.Roles = new SelectList(roles);
            return(View());
        }
        protected List <Credential> getCredentials(HttpContextBase httpContext)
        {
            IdentityDb _db = new IdentityDb();

            // Primeiramente, selecionamos os papeis do usuário logado
            List <string> usrRoles = _db.Users
                                     .Where(u => u.UserName == httpContext.User.Identity.Name)
                                     .FirstOrDefault().Roles.Select(r => r.RoleId).ToList();

            // Em seguida, selecionamos todas as credenciais deste usuário
            List <Credential> usrCredentials = _db.ApplicationRoles.Join(usrRoles,
                                                                         a => a.Id,
                                                                         r => r,
                                                                         (a, r) => a).SelectMany(c => c.Credentials).ToList();

            return(usrCredentials);
        }
        public IHttpActionResult GetAccounts()
        {
            List<UserModel> listProviders = new List<UserModel>();
            var restaurantId = ((ClaimsIdentity)User.Identity).GetUserId();
            var providersIds = new List<String>();
            var us = new List<userDemo>();

            using (var db =  new RPDb())
            {
                providersIds = db.RestaurantProvedors.Where(r => r.RestaurantId == restaurantId).Select(s=> s.ProviderId).ToList();
            }
                using (var context = new IdentityDb())
            {
                us = context.Users.Where(x => providersIds.Contains(x.Id)).Select(u => new userDemo{ Name = u.UserName }).ToList();
            }

            return Ok(us);
        }
 private static void AddLanguages(this IdentityDb db)
 {
     if (!db.Languages.Any())
     {
         db.Languages.AddRange(new Language()
         {
             Name = "English"
         },
                               new Language()
         {
             Name = "فارسی"
         },
                               new Language()
         {
             Name = "Malay"
         });
         db.SaveChanges();
     }
 }
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            using (var db = new IdentityDb())
            {
                db.Database.Log = (c) => { System.Diagnostics.Debug.WriteLine(c); };

                foreach (var iclaim in userIdentity.Claims)
                {
                    if (acceptedClaims.Contains(iclaim.Type))
                    {
                        var usr = await manager.FindByIdAsync(this.Id);

                        var claim = usr.Claims.Where(c => c.ClaimType == iclaim.Type).FirstOrDefault();

                        if (claim == null)
                        {
                            usr.Claims
                            .Add(new UserClaimIntPk
                            {
                                ClaimType  = iclaim.Type,
                                ClaimValue = iclaim.Value,
                                UserId     = this.Id
                            });
                        }
                        else
                        {
                            if (claim.ClaimValue != iclaim.Value)
                            {
                                claim.ClaimValue      = iclaim.Value;
                                db.Entry(claim).State = System.Data.Entity.EntityState.Modified;
                            }
                        }
                    }
                }
                db.SaveChanges();
            }
            return(userIdentity);
        }
Exemple #26
0
        // In this method we will create default User roles and Admin user for login
        private void createRolesandUsers()
        {
            IdentityDb context = new IdentityDb();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            // In Startup iam creating first Admin Role
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }

            // creating Creating Manager role
            if (!roleManager.RoleExists("User"))
            {
                var role = new IdentityRole();
                role.Name = "User";
                roleManager.Create(role);
            }
        }
Exemple #27
0
        public static bool HasCredentials(string user, string action, string controller, string param = null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                IdentityDb _db = new IdentityDb();

                // Primeiramente, selecionamos os papeis do usuário logado
                List <string> usrRoles = _db.Users
                                         .Where(u => u.UserName == user)
                                         .FirstOrDefault().Roles.Select(r => r.RoleId).ToList();

                // Em seguida, selecionamos todas as credenciais deste usuário
                List <Credential> usrCredentials = _db.ApplicationRoles.Join(usrRoles,
                                                                             a => a.Id,
                                                                             r => r,
                                                                             (a, r) => a).SelectMany(c => c.Credentials).ToList();

                return(usrCredentials.Where(c => c.Action.Contains(action) && c.Controller == controller && c.Param == param).Count() > 0);
            }
            else
            {
                return(false);
            }
        }
        public async Task AddUser(IdentityDb db)
        {
            if (!_userManager.Users.Any())
            {
                Guid lanId = db.Languages.FirstOrDefault(l => l.Name == "English").Id;
                Guid CurId = db.Currencies.FirstOrDefault(c => c.Name == "RM").Id;

                var result = await _userManager.CreateAsync(
                    new User()
                {
                    FirstName  = "Mona",
                    LastName   = "Moravej",
                    UserName   = "******",
                    Email      = "*****@*****.**",
                    LanguageId = lanId,
                    CurrencyId = CurId
                }, "Mona1!");

                if (!result.Succeeded)
                {
                    throw new InvalidOperationException("Failed to build user and roles");
                }
            }
        }
Exemple #29
0
 public RolesController()
 {
     _db = new IdentityDb();
 }
 public CurrentUser(IIdentity identity, IdentityDb context)
 {
     _identity = identity;
     _context = context;
 }
 public SeedData(IdentityDb context)
 {
     _context = context;
 }
Exemple #32
0
 public AccountController()
 {
     context = new IdentityDb();
 }
        public IHttpActionResult GetNotifications(int isProvider)
        {
            // GGMS Quien hace el request. de los provedores
            // en un punto esto va a tener que recibir un parametro de que cocina.. quiere ver el provider
            var providerId = ((ClaimsIdentity)User.Identity).GetUserId();
            var id = db.RestaurantProvedors.Where(r=> r.ProviderId == providerId).Select(s=>s.RestaurantId).FirstOrDefault();

            // Last Notification of Restaurant Related
            //  var id = ((ClaimsIdentity)User.Identity).GetUserId();
            //   var notification = db.Notifications.Where(x=> x.RestaurantId == id);
            var context = new IdentityDb();
            var us = context.Users.Where(x => x.Id == id).Select(u=> u.CompanyName).FirstOrDefault();
            context.Dispose();
            //   NotificationView obj = new NotificationView();

            var dueDate = DateTime.Now;

            var notificationsOrigin = db.Notifications
                   .Where(i => i.RestaurantId == id && i.IsActive == true && dueDate < i.DueDate)
                   .Select(m => new NotificationView
                   {
                       NotificationId = m.NotificationId,
                      Restaurant = us,
                       CreatedDate = m.CreatedDate,
                       DueDate = m.DueDate,
                       IngNotificationViews = db.IngNotifications.Where(d => d.NotificationId == m.NotificationId && m.IsActive == true).Select(dd => new IngNotificationView
                       {
                           IngNotificationId = dd.IngNotificationId,
                         unitMeasureRestaurant = db.Ingredients.Where(ingI => ingI.IngredientId == dd.IngDish.IngredientId).Select(x=> x.Unit.Name).FirstOrDefault(),
                           // IngredientName = db.IngNotifications.Include(inc => inc.IngDish).Where(inf => inf.IngDishId == dd.IngDishId).Select(infI => infI.IngDish.Ingredient.Name).FirstOrDefault(),
                           IngredientName = db.Ingredients.Where(ingI=> ingI.IngredientId == dd.IngDish.IngredientId).Select(name => name.Name).FirstOrDefault(),
                           TotalRequired = dd.TotalRequired,
                           UnitCost = decimal.Zero

                       }).ToList()
                   }).FirstOrDefault();

            //    ProviderName = db.
            //    CreatedDate =

            //    IngNotificationView objIng1 = new IngNotificationView();
            //    IngredientName =
            //    IngNotificationId =
            //    TotalRequired =
            //    UnitCost =
            //    DateExpired =

            //    obj.IngNotificationViews.Add(objIng1);

            //IngNotificationView objIng2 = new IngNotificationView();
            //    IngredientName =
            //    IngNotificationId =
            //    TotalRequired =
            //    UnitCost =
            //    DateExpired =

            //    obj.IngNotificationViews.Add(objIng2);

            //var userId = ((ClaimsIdentity)User.Identity).GetUserId();
            //Notification notification = db.Notifications
            //    .Include(p => p.IngNotifications.Select(s => s.IngNotiPosts))
            //    .Where(n => n.NotificationId == id && n.RestaurantId == userId)
            //    .FirstOrDefault();

            if (notificationsOrigin == null)
            {
                return NotFound();
            }

            return Ok(notificationsOrigin);
        }
        internal static void RandomDogOwners(this IdentityDb context, int numberOfDogOwners, int emailLength, int phoneLength)
        {
            #region Helpers

            string[] EmailExtensions = new string[]
            {
                "@gmail.com", "@yahoo.com", "@outlook.com", "@yandex.com", "@aol.com", "@zoho.com", "@mail.com", "@tutanota.com"
            };

            string[] listFullNames = new string[]
            {
                "Lisette Gerhardt", "Kandis Paredes", "Carolee Ardis", "Debbi Monti", "John Chapman", "Francine Rosalez",
                "Rosette Hawkin", "Josie Poff", "Nadene Arnette", "Quinn Sharpe", "Breanna Costigan", "Reinaldo Tyra",
                "Stuart Easter", "Georgiana Molina", "Kira Pilkenton", "Olevia Coogan", "Cassaundra Breen", "Rosana Towner",
                "Georgetta Edinger", "Monique Bottomley", "Nathanial Nemitz", "Cheri Fender", "Claire Deibert", "Indira Flatt",
                "Sterling Kunz", "Lakendra Sowers", "Tandra Siguenza", "Angelique Nott", "Valrie Mcmiller", "Amina Paulos",
                "Rosetta Cervone", "Edgar Deharo", "Jacinta Mays", "Aldo Parsley", "Nelda Oritz", "Elroy Hallee", "Kathryn Enochs",
                "Thi Clift", "Arturo Vrba", "Forrest Natali", "Lorilee Herdt", "Marry Cottrell", "Manuela Musto", "Sheena Finney",
                "Audie Penny", "Ja Keogh", "Margurite Linney", "Ying Eble", "Tory Hennessy", "Somer Breed"
            };

            string RandomEmail(int numberOfLetters)
            {
                byte[] allLetters = new byte[numberOfLetters];

                for (int letter = 0; letter < numberOfLetters; letter++)
                {
                    if (letter == 0)
                    {
                        allLetters[letter] = (byte)random.Next(65, 91);
                        continue;
                    }
                    allLetters[letter] = (byte)random.Next(97, 123);
                }

                return(Encoding.ASCII.GetString(allLetters) + EmailExtensions[random.Next(EmailExtensions.Length)]);
            }

            string RandomPhoneNumber(int numberOfDigits)
            {
                char[] phoneLenght = new char[numberOfDigits];
                phoneLenght[0] = '0';
                phoneLenght[1] = '7';
                for (int i = 2; i < numberOfDigits; i++)
                {
                    if (i == 2)
                    {
                        phoneLenght[i] = random.Next(4).ToString()[0];
                        continue;
                    }

                    phoneLenght[i] = random.Next(10).ToString()[0];
                }

                return(new string(phoneLenght));
            }

            string RandomFullName()
            {
                return(listFullNames[random.Next(listFullNames.Length)]);
            }

            #endregion

            using (TransactionScope scope = new TransactionScope())
            {
                using (context = new IdentityDb())
                {
                    var haser = new PasswordHasher();
                    for (int i = 0; i < numberOfDogOwners; i++)
                    {
                        string userEmail = RandomEmail(emailLength);
                        string password  = "******";
                        string fullName  = RandomFullName();

                        var user = new ApplicationUser()
                        {
                            FirstName      = fullName.Split(null)[0],
                            LastName       = fullName.Split(null)[1],
                            PhoneNumber    = RandomPhoneNumber(9),
                            UserName       = userEmail,
                            Email          = userEmail,
                            IsConfirmed    = random.NextDouble() > 0.5,
                            LockoutEnabled = true,
                            PasswordHash   = haser.HashPassword(password)
                        };

                        context.Users.Add(user);

                        if (i % 100 == 0)
                        {
                            context.SaveChanges();
                            context.Dispose();
                            context = new IdentityDb();
                        }
                    }
                    context.SaveChanges();
                }
                scope.Complete();
            }
        }
 public CribsController()
 {
     db = new IdentityDb();
 }
 public HomeController(IdentityDb content)
 {
     _content = content;
 }
        // GET: api/Orders
        public List<getOrdersDTO> GetOrders()
        {
            var userId = ((ClaimsIdentity)User.Identity).GetUserId();
            var context = new IdentityDb();
            // Orders for Providers
            var objOrders = db.Orders
                 .Include(i => i.IngOrders)
                 .Include(c => c.IngOrders.Select(s => s.IngNotiPost))
                 .Where(x => x.RestaurantId == userId)
                 .Select(ordR => new getOrdersDTO {
                     orderId = ordR.OrderId,
                     providerId = ordR.IngOrders.Select(inp => inp.IngNotiPost.ProviderId).FirstOrDefault(),
                     restaurantId= ordR.RestaurantId,
                     createdDate = ordR.CreatedDate,
                     status= ordR.Status,
                     totalcost = ordR.TotalCost
                 }).ToList();

            foreach ( var addmissing in objOrders) {

                addmissing.providerName = context.Users.Where(x => x.Id == addmissing.providerId).Select(u => u.CompanyName).FirstOrDefault();
                addmissing.restaurantName = context.Users.Where(x => x.Id == addmissing.restaurantId).Select(u => u.CompanyName).FirstOrDefault();
            }

            // Orders for Restaurant
            var obj = db.Orders
              .Include(i => i.IngOrders)
              .Include(c => c.IngOrders.Select(s => s.IngNotiPost))
              .Where(x => x.RestaurantId == userId);

            // return db.Orders;
            return objOrders;
        }
 private async Task<IdentityResult> ChangeEmailAsync(string v, string newEmail)
 {
     var db = new IdentityDb();
     var user = db.Users.FirstOrDefaultAsync(x => x.Id == User.Identity.GetUserId());
     user.Result.Email = newEmail;
     await db.SaveChangesAsync();
     return await Task.FromResult(IdentityResult.Success);
 }
Exemple #39
0
 public AuthRepository()
 {
     _ctx = new IdentityDb();
     _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_ctx));
 }
        public IHttpActionResult GetIngNotiPosts(int id)
        {
            //IngNotiPost ingNotiPost = db.IngNotiPosts.Find(id);

            // definitivamente esto necesitara refactoring por que ... hace demaciadas llamadas a db.
            GetIngPostDTO getPost = new GetIngPostDTO();
            var restaurantId = ((ClaimsIdentity)User.Identity).GetUserId();

            // get LastNotification Created. This can be used to get the specific when we get the method
            var lastNoty = (from ingN in db.IngNotifications
                            join notys in db.Notifications on ingN.NotificationId equals notys.NotificationId
                            where notys.RestaurantId == restaurantId
                            && notys.NotificationId == id
                            select new { ingN.IngNotificationId }).ToList();
            List<int> intlastNoty = lastNoty.Select(s => s.IngNotificationId).ToList<int>();
            //.Where(n => n.RestaurantId == restaurantId).OrderByDescending(o => o.CreatedDate).SingleOrDefault();)
            var context = new IdentityDb();

            var IngNotiPostsList = db.IngNotiPosts
                .Include(ix => ix.IngNotification.IngDish.Ingredient.Unit)
                .Where(r => r.RestaurantId == restaurantId && intlastNoty.Contains(r.IngNotificationId))
                .ToList();

            var providersXX = IngNotiPostsList.GroupBy(s => s.ProviderId);

            List<ProvidersIP> providers = new List<ProvidersIP>();
            List<PostIP> posts = new List<PostIP>();
            foreach (IGrouping<string, IngNotiPost> p in providersXX)
            {

                var userI = p.Select(d => d.ProviderId).FirstOrDefault();
                var ri = context.Users.Where(x => x.Id == userI).Select(u => u.Id).FirstOrDefault();
                var rn = context.Users.Where(x => x.Id == ri).Select(u => u.CompanyName).FirstOrDefault();

                providers.Add(new ProvidersIP
                {
                    Providerid = ri,
                    Name = rn
                });

            }

            var postXX = IngNotiPostsList.GroupBy(s => s.IngNotification.IngDish.IngredientId);
            int postOrder = 0;
            foreach (IGrouping<int, IngNotiPost> pp in postXX)
            {
                var or = postOrder++;
                PostIP postX = new PostIP();
                postX.ingCost = new List<IngCostIP>();
                postX.PostId = or;//pp.Select(PostId => PostId.IngNotiPostId).FirstOrDefault();
                postX.IngName = pp.Select(IngName => IngName.IngNotification.IngDish.Ingredient.Name).FirstOrDefault();
                postX.Required = pp.Select(Required => Required.IngNotification.TotalRequired).FirstOrDefault();
                postX.MeasureUnit = pp.Select(MeasureUnit => MeasureUnit.IngNotification.IngDish.Ingredient.Unit.Name).FirstOrDefault();

                foreach (var ing in pp)
                {
                    //   for (int pIndex = 0; pIndex < providers.Count; pIndex++) {

                    var userI = pp.Select(d => ing.ProviderId).FirstOrDefault();
                    var ri = context.Users.Where(x => x.Id == userI).Select(u => u.Id).FirstOrDefault();
                    var rn = context.Users.Where(x => x.Id == ri).Select(u => u.CompanyName).FirstOrDefault();

                    //var userI = pp.Select(d => d.ProviderId).FirstOrDefault();
                    //var ri = context.Users.Where(x => x.Id == userI).Select(u => u.Id).FirstOrDefault();
                    //var rn = context.Users.Where(x => x.Id == ri).Select(u => u.CompanyName).FirstOrDefault();

                    IngCostIP ingCostp = new IngCostIP();
                    ingCostp.ingCostId = ing.IngNotiPostId;
                    ingCostp.UnitCost = ing.UnitCost;
                    ingCostp.Data = "";
                    ingCostp.Providerid = ri;
                    ingCostp.Provname = rn;
                    ingCostp.PostId = or;

                    //ingCostp.ingCostId = pp.Select(ingCostId=> ingCostId.IngNotiPostId).FirstOrDefault()==0 ? 0: pp.Select(ingCostId => ingCostId.IngNotiPostId).FirstOrDefault();
                    //ingCostp.UnitCost = pp.Select(UnitCost => UnitCost.UnitCost).FirstOrDefault() == 0 ? 0 : pp.Select(UnitCost => UnitCost.UnitCost).FirstOrDefault();
                    //ingCostp.Data = "";
                    //ingCostp.Providerid = ri;
                    //ingCostp.Provname = rn;
                    //ingCostp.PostId = or;

                    postX.ingCost.Add(ingCostp);
                }

                for (int pIndex = 0; pIndex < providers.Count; pIndex++)
                {

                    if (!postX.ingCost.Any(x => x.Providerid == providers[pIndex].Providerid))
                    {

                        var userI = pp.Select(d => providers[pIndex].Providerid).FirstOrDefault();
                        var ri = context.Users.Where(x => x.Id == userI).Select(u => u.Id).FirstOrDefault();
                        var rn = context.Users.Where(x => x.Id == ri).Select(u => u.CompanyName).FirstOrDefault();

                        IngCostIP ingCostp = new IngCostIP();
                        ingCostp.ingCostId = 0;
                        ingCostp.UnitCost = 0;
                        ingCostp.Data = "";
                        ingCostp.Providerid = ri;
                        ingCostp.Provname = rn;
                        ingCostp.PostId = or;
                        postX.ingCost.Add(ingCostp);
                    }
                }

                posts.Add(postX);
            }

            //PostIP postX = new PostIP();
            //postX.PostId = p.Select(PostId => PostId.IngNotificationId).FirstOrDefault();
            //postX.IngName = p.Select(IngName => IngName.IngNotification.IngDish.Ingredient.Name).FirstOrDefault();
            //postX.Required = p.Select(Required => Required.IngNotification.TotalRequired).FirstOrDefault();
            //postX.MeasureUnit = t.IngNotification.IngDish.Ingredient.Unit.Name).FirstOrDefault();

            //foreach (var t in p)
            //    posts.Add(new PostIP
            //    {
            //        PostId = t.IngNotificationId,
            //        PostId = t.IngNotification.IngDish.Ingredient.Name,
            //        Required = t.IngNotification.TotalRequired,
            //        MeasureUnit = t.IngNotification.IngDish.Ingredient.Unit.Name,
            //        ingCosts = db.IngNotiPosts.Where(rx => t.IngNotiPostId == rx.IngNotiPostId).Select(srx => new IngCostIP
            //        {
            //            ingCostId = srx.IngNotiPostId,
            //            UnitCost = srx.UnitCost,
            //            Data = "",
            //            Providerid = ri,
            //            Provname = rn,
            //            PostId = t.IngNotificationId,
            //        }).ToList()

            //    });

            // var posts = db.IngNotiPosts.Include(ix=> ix.IngNotification.IngDish.Ingredient)
            //.Where(r => r.RestaurantId == restaurantId && intlastNoty.Contains(r.IngNotificationId))
            //.Select(s => new PostIP
            //{
            //   PostId = s.IngNotificationId,
            //   IngName = s.IngNotification.IngDish.Ingredient.Name,
            //   Required = s.IngNotification.TotalRequired,
            //   MeasureUnit = s.IngNotification.IngDish.Ingredient.Unit.Name,
            //   ingCosts = db.IngNotiPosts.Where(rx=> s.IngNotiPostId == rx.IngNotiPostId).Select(srx=> new IngCostIP {
            //       ingCostId = srx.IngNotificationId,
            //       UnitCost = srx.UnitCost,
            //       Data = "",
            //       Providerid = context.Users.Where(x => x.Id == s.ProviderId).Select(u => int.Parse(u.Id)).FirstOrDefault(),
            //       Provname = context.Users.Where(x => x.Id == s.ProviderId).Select(u => u.CompanyName).FirstOrDefault(),
            //       PostId = s.IngNotificationId
            //   }).ToList()

            //}).ToList();

            getPost.providers = providers;
            getPost.posts = posts;

            context.Dispose();

            if (getPost == null)
            {
                return NotFound();
            }

            return Ok(getPost);
        }
Exemple #41
0
 public RolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
 {
     _db         = new IdentityDb();
     UserManager = userManager;
     RoleManager = roleManager;
 }