Exemplo n.º 1
0
 // GET: Dishes/Create
 public ActionResult Create()
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         ViewBag.DishCategoryID = new SelectList(db.DishCategories, "ID", "Name");
         return(View());
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 2
0
 // GET: Dishes
 public ActionResult Index()
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         var dishes = db.Dishes.Include(d => d.DishCategory);
         return(View(dishes.ToList()));
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 3
0
 public ActionResult DeleteConfirmed(int id)
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         Dish dish = db.Dishes.Find(id);
         db.Dishes.Remove(dish);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 4
0
        // GET: Companies/Create
        public ActionResult Create()
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            ViewBag.StatusID = new SelectList(db.States, "ID", "Name");
            ViewBag.LevelID  = new SelectList(db.Levels, "ID", "Name");
            return(View());
        }
Exemplo n.º 5
0
        // GET: Companies
        public ActionResult Index()
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            var companies = db.Companies.Include(c => c.State).Include(c => c.Level);

            return(View(companies.ToList()));
        }
Exemplo n.º 6
0
        public ActionResult DeleteConfirmed(int id)
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            Company company = db.Companies.Find(id);

            db.Companies.Remove(company);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 7
0
        public async Task <IHttpActionResult> GetLocalExternalAccessToken(string provider, string externalAccessToken, string client_id, string client_secret = "")
        {
            if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(externalAccessToken))
            {
                return(BadRequest("Provider or external access token is not sent"));
            }
            KeyValuePair <string, Func <ITokenInfo> > searchExternalProvider;

            try
            {
                searchExternalProvider = WebApiApplication.TokenInfoList.First(x => x.Key == provider);
            }
            catch (InvalidOperationException)
            {
                ModelState.AddModelError("Provider", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            var instance = searchExternalProvider.Value.Invoke();
            var verifiedTokenExternal = await instance.Get(externalAccessToken);

            if (verifiedTokenExternal == null)
            {
                ModelState.AddModelError(GenericNames.AUTHENTICATION_EXTERNAL_LOGIN, GenericError.INVALID_GIVEN_PARAMETER);
                return(BadRequest(ModelState));
            }
            Client userClient = await Manager.FindAsync(new UserLoginInfo(provider, verifiedTokenExternal.user_id));

            if (userClient == null)
            {
                ModelState.AddModelError("Client", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            Service service = null;

            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(Request.GetOwinContext().Get <ManahostManagerDAL>(), client_id, client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                ModelState.AddModelError(e.Key, e.Value);
                return(BadRequest(ModelState));
            }
            var ticket = AuthenticationTools.GenerateTicket(OAuthDefaults.AuthenticationType, client_id, userClient);
            var accessTokenExternal = AuthenticationTools.GenerateToken(ticket, userClient);

            return(OkWithHeader(accessTokenExternal, new Dictionary <string, string>()
            {
                { GenericNames.OWIN_CONTEXT_CORS_HEADER, service.AllowedOrigin }
            }));
        }
Exemplo n.º 8
0
 public ActionResult Edit([Bind(Include = "Name,Price,DishCategoryID")] Dish dish)
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         if (ModelState.IsValid)
         {
             db.Entry(dish).State = EntityState.Modified;
             db.SaveChanges();
             return(RedirectToAction("Index"));
         }
         ViewBag.DishCategoryID = new SelectList(db.DishCategories, "ID", "Name", dish.DishCategoryID);
         return(View(dish));
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 9
0
 // GET: Dishes/Details/5
 public ActionResult Details(int?id)
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         Dish dish = db.Dishes.Find(id);
         if (dish == null)
         {
             return(HttpNotFound());
         }
         return(View(dish));
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 10
0
 // GET: Dishes/Edit/5
 public ActionResult Edit(int?id)
 {
     if (AuthenticationTools.UserHasRole(currentUserName, "StaffMember,Boss,Admin"))
     {
         if (id == null)
         {
             return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
         }
         Dish dish = db.Dishes.Find(id);
         if (dish == null)
         {
             return(HttpNotFound());
         }
         ViewBag.DishCategoryID = new SelectList(db.DishCategories, "ID", "Name", dish.DishCategoryID);
         return(View(dish));
     }
     return(RedirectToAction("Login", "Account"));
 }
Exemplo n.º 11
0
        // GET: Companies/Details/5
        public ActionResult Details(int?id)
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Company company = db.Companies.Find(id);

            if (company == null)
            {
                return(HttpNotFound());
            }
            return(View(company));
        }
Exemplo n.º 12
0
        public ActionResult Create([Bind(Include = "Name,StatusID,LevelID")] Company company)
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (ModelState.IsValid)
            {
                company.StatusID = 1;
                db.Companies.Add(company);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.StatusID = new SelectList(db.States, "ID", "Name", company.StatusID);
            ViewBag.LevelID  = new SelectList(db.Levels, "ID", "Name", company.LevelID);

            return(View(company));
        }
Exemplo n.º 13
0
        public ActionResult Edit(Company company)
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (ModelState.IsValid)
            {
                Company nc = db.Companies.Where(x => x.ID == company.ID).FirstOrDefault();
                nc.Name            = company.Name;
                nc.LevelID         = company.LevelID;
                db.Entry(nc).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.StatusID = new SelectList(db.States, "ID", "Name", company.StatusID);
            ViewBag.LevelID  = new SelectList(db.Levels, "ID", "Name", company.LevelID);

            return(View(company));
        }
Exemplo n.º 14
0
        // GET: Companies/Edit/5
        public ActionResult Edit(int?id)
        {
            if (!AuthenticationTools.UserHasRole(currentUser, "Boss,Admin"))
            {
                return(RedirectToAction("Login", "Account"));
            }

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Company company = db.Companies.Find(id);

            if (company == null)
            {
                return(HttpNotFound());
            }
            ViewBag.StatusID = new SelectList(db.States, "ID", "Name", company.StatusID);
            ViewBag.LevelID  = new SelectList(db.Levels, "ID", "Name", company.LevelID);

            return(View(company));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Methode qui permet la validation du Service AKA Client web ou mobile, via le client_id et optionnellement le client_secret.
        /// </summary>
        /// <param name="context">Le context de la requête et d'autre information utiles à la gestion du service</param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string client_id     = string.Empty;
            string client_secret = string.Empty;

            if (!context.TryGetBasicCredentials(out client_id, out client_secret))
            {
                context.TryGetFormCredentials(out client_id, out client_secret);
            }
            Service service = null;

            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(context.OwinContext.Get <ManahostManagerDAL>(), context.ClientId, client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                context.SetError(e.Key, e.Value);
                return;
            }
            context.OwinContext.Set <string>(GenericNames.OWIN_CONTEXT_CORS, service.AllowedOrigin);
            context.OwinContext.Set <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME, service.RefreshTokenLifeTime);
            context.Validated();
        }
Exemplo n.º 16
0
        public async Task <IHttpActionResult> PostRegisterExternel(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            KeyValuePair <string, Func <ITokenInfo> > searchExternalProvider;

            try
            {
                searchExternalProvider = WebApiApplication.TokenInfoList.First(x => x.Key == model.Provider);
            }
            catch (InvalidOperationException)
            {
                ModelState.AddModelError("Provider", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            var instance    = searchExternalProvider.Value.Invoke();
            var parsedToken = await instance.Get(model.ExternalAccessToken);

            if (parsedToken == null)
            {
                ModelState.AddModelError(GenericNames.AUTHENTICATION_EXTERNAL_LOGIN, GenericError.INVALID_GIVEN_PARAMETER);
                return(BadRequest(ModelState));
            }
            Client user = await Manager.FindAsync(new UserLoginInfo(model.Provider, parsedToken.user_id));

            if (user != null)
            {
                ModelState.AddModelError("Client", GenericError.ALREADY_EXISTS);
                return(BadRequest(ModelState));
            }

            var informationUser = await instance.GetUserInfo(model.ExternalAccessToken);

            var client       = Factory.Create(informationUser);
            var resultClient = await Manager.CreateAsync(client);

            if (!resultClient.Succeeded)
            {
                //TODO ERROR
                return(BadRequest());
            }
            var ResultLoginClient = await Manager.AddLoginAsync(client.Id, new UserLoginInfo(model.Provider, parsedToken.user_id));

            if (!ResultLoginClient.Succeeded)
            {
                //TODO ERROR
                return(BadRequest());
            }
            Service service = null;

            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(Request.GetOwinContext().Get <ManahostManagerDAL>(), model.client_id, model.client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                ModelState.AddModelError(e.Key, e.Value);
                return(BadRequest(ModelState));
            }
            var ticket = AuthenticationTools.GenerateTicket(OAuthDefaults.AuthenticationType, model.client_id, client);
            var accessTokenExternal = AuthenticationTools.GenerateToken(ticket, client);

            return(OkWithHeader(accessTokenExternal, new Dictionary <string, string>()
            {
                { GenericNames.OWIN_CONTEXT_CORS_HEADER, service.AllowedOrigin }
            }));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Methode qui sert à la vérification de l'authentification du client
        /// </summary>
        /// <param name="context">Le context de la requête et d'autre information utiles à la gestions du service</param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            IDependencyScope  Scope        = context.OwinContext.Get <IDependencyScope>();
            ClientUserManager manager      = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            ClientRoleManager managerRoles = Scope.GetService(typeof(ClientRoleManager)) as ClientRoleManager;

            /*ClientUserManager manager = context.OwinContext.GetUserManager<ClientUserManager>();
             * ClientRoleManager managerRoles = context.OwinContext.Get<ClientRoleManager>();*/

            var AllowOriginCORS      = context.OwinContext.Get <string>(GenericNames.OWIN_CONTEXT_CORS);
            var attempt              = Convert.ToInt32(ConfigurationManager.AppSettings[GenericNames.CAPTCHA_FAILED_COUNT]);
            int RefreshTokenLifeTime = context.OwinContext.Get <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME);

            if (AllowOriginCORS == null)
            {
                AllowOriginCORS = "*";
            }

            context.OwinContext.Response.Headers.Remove(GenericNames.OWIN_CONTEXT_CORS_HEADER);
            context.OwinContext.Response.Headers.Add(GenericNames.OWIN_CONTEXT_CORS_HEADER, new[] { AllowOriginCORS });

            Client user = await manager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                Client FindByEmail = await manager.FindByEmailAsync(context.UserName);

                if (FindByEmail != null)
                {
                    FindByEmail.AccessFailedCount++;
                    FindByEmail.LastAttemptConnexion = DateTime.UtcNow;
                    await manager.UpdateAsync(FindByEmail);

                    if (FindByEmail.AccessFailedCount > attempt)
                    {
                        context.SetError("captcha", GenericError.NEED_CAPTCHA);
                        return;
                    }
                }
                context.SetError("invalid_grant", GenericError.INVALID_GIVEN_PARAMETER);
                return;
            }
            if (!user.EmailConfirmed)
            {
                context.SetError("email_confirmation", GenericError.EMAIL_NOT_CONFIRMED);
                return;
            }
            if (user.LockoutEnabled)
            {
                context.SetError("client", GenericError.ACCOUNT_DISABLED);
                return;
            }

            AuthenticationTicket ticket = null;

            if (user.AccessFailedCount > attempt)
            {
                var data = await context.Request.ReadFormAsync();

                var Code = data[GenericNames.GOOGLE_RECAPTCHA_FORM];
                if (Code == null)
                {
                    context.SetError("captcha", GenericError.CAPTCHA_MISSING_RESPONSE);
                    return;
                }
                else
                {
                    ICaptchaTools tools       = GoogleReCaptchValidator.Create();
                    var           testCaptcha = await tools.VerifyCaptcha(Code, context.Request.RemoteIpAddress);

                    if (testCaptcha)
                    {
                        user.AccessFailedCount = 0;
                        await manager.UpdateAsync(user);

                        ticket = AuthenticationTools.GenerateTicket(context.Options.AuthenticationType, context.ClientId, user, RefreshTokenLifeTime);
                    }
                    else
                    {
                        context.SetError("captcha", GenericError.CAPTCHA_INVALID_SOLUTION);
                        return;
                    }
                }
            }
            else
            {
                ticket = AuthenticationTools.GenerateTicket(context.Options.AuthenticationType, context.ClientId, user, RefreshTokenLifeTime);
            }

            context.Validated(ticket);
        }