Exemplo n.º 1
0
        // public
        static public Task <ActionResult> ProcessQuery <T>(IIdentity user, HttpRequest uriInfo, DbContext entityManager, String serviceName) where T : class
        {
            IQueryCollection queryParameters = uriInfo.Query;

            DbUtils.QueryMap fields  = RequestFilter.ParseQueryParameters((LoginResponse)user, serviceName, queryParameters);
            String[]         orderBy = null;

            {
                CrudService service = RequestFilter.GetService(user, serviceName);

                if (service.OrderBy != null)
                {
                    orderBy = service.OrderBy.Split(',');
                }
            }

            int?startPosition = null;
            int?maxResult     = null;

            startPosition = queryParameters["start"].Count == 1 ? int.Parse(queryParameters["start"]) : startPosition;
            maxResult     = queryParameters["max"].Count == 1 ? int.Parse(queryParameters["max"]) : maxResult;
            Type entityClass = RequestFilter.mapClass[serviceName];

            return(DbUtils.Find <T>(entityManager, entityClass, fields, orderBy, startPosition, maxResult).ContinueWith(taskResults => {
                if (taskResults.Exception != null)
                {
                    return Response.BadRequest("ProcessQuery.Find : " + taskResults.Exception.Message);
                }

                ActionResult response = Response.Ok(taskResults.Result);
                return response;
            }));
        }
Exemplo n.º 2
0
 // public processDelete
 static public Task <ActionResult> ProcessDelete <T>(IIdentity user, HttpRequest uriInfo, DbContext entityManager, String serviceName) where T : class
 {
     return(RequestFilter.GetObject <T>(user, uriInfo, entityManager, serviceName).ContinueWith <ActionResult>(taskGet => {
         return DbUtils.DeleteOne <T>(entityManager, taskGet.Result).ContinueWith <ActionResult>((taskObjDeleted) => {
             RequestFilter.Notify(taskObjDeleted.Result, serviceName, true);
             return Response.Ok();
         }, TaskContinuationOptions.NotOnFaulted).Result;
     }, TaskContinuationOptions.NotOnFaulted));
 }
Exemplo n.º 3
0
        // private
        static private DbUtils.QueryMap ParseQueryParameters(LoginResponse login, String serviceName, IQueryCollection queryParameters)
        {
            CrudService service = RequestFilter.GetService(login, serviceName);

            DbUtils.QueryMap queryFields   = DbUtils.QueryMap.Create();
            JObject          serviceFields = JObject.Parse(service.Fields);

            foreach (var item in serviceFields)
            {
                JToken field = item.Value;

                if (field.Value <Boolean> ("primaryKey") == true)
                {
                    StringValues values = queryParameters [item.Key];

                    if (values.Count > 0)
                    {
                        String type = field.Value <String> ("type");

                        if (type == null || type.Equals("s"))
                        {
                            queryFields.Add(item.Key, values.First());
                        }
                        else if (type.Equals("n") || type.Equals("i"))
                        {
                            queryFields.Add(item.Key, int.Parse(values.First()));
                        }
                        else if (type.Equals("b"))
                        {
                            queryFields.Add(item.Key, Boolean.Parse(values.First()));
                        }
                    }
                }
            }
            // se não for admin, limita os resultados para as crudGroup vinculadas a empresa do usuário
            int?crudGroupOwner = login.user.CrudGroupOwner;

            if (crudGroupOwner != 1)
            {
                if (serviceFields.ContainsKey("crudGroupOwner"))
                {
                    queryFields["crudGroupOwner"] = crudGroupOwner;
                }
                else if (serviceFields.ContainsKey("crudGroup"))
                {
                    queryFields["crudGroup"] = login.groups;
                }
            }

            return(queryFields);
        }
Exemplo n.º 4
0
        // public
        static public Task <ActionResult> ProcessCreate <T>(IIdentity user, DbContext entityManager, String serviceName, T obj) where T : class
        {
            ActionResult response = RequestFilter.CheckObjectAccess(user, serviceName, obj);

            if (response != null)
            {
                return(Task.Run(() => response));
            }

            return(DbUtils.Insert <T>(null, entityManager, obj).ContinueWith <ActionResult>(taskInsert => {
                Object newObj = taskInsert.Result;
                RequestFilter.Notify(newObj, serviceName, false);
                return Response.Ok(newObj);
            }, TaskContinuationOptions.NotOnFaulted));
        }
Exemplo n.º 5
0
        // public processUpdate
        static public Task <ActionResult> ProcessUpdate <T>(IIdentity user, HttpRequest uriInfo, DbContext entityManager, String serviceName, T obj) where T : class
        {
            return(RequestFilter.GetObject <T>(user, uriInfo, entityManager, serviceName).ContinueWith <ActionResult>(taskGet => {
                ActionResult response = CheckObjectAccess(user, serviceName, obj);

                if (response != null)
                {
                    return response;
                }

                entityManager.Entry(taskGet.Result).State = EntityState.Detached;
                return DbUtils.Update <T>(null, entityManager, obj).ContinueWith <ActionResult>(taskNewObj => {
                    RequestFilter.Notify(taskNewObj.Result, serviceName, false);
                    return Response.Ok(taskNewObj.Result);
                }, TaskContinuationOptions.NotOnFaulted).Result;
            }, TaskContinuationOptions.NotOnFaulted));
        }
Exemplo n.º 6
0
// private to create,update,delete,read
        static private ActionResult CheckObjectAccess(IIdentity user, String serviceName, Object obj)
        {
            CrudService service;

            try {
                service = RequestFilter.GetService(user, serviceName);
            } catch (Exception e) {
                return(Response.Unauthorized(e.Message));
            }

            LoginResponse login              = (LoginResponse)user;
            JObject       serviceFields      = JObject.Parse(service.Fields);
            ActionResult  response           = null;
            int?          userCrudGroupOwner = login.user.CrudGroupOwner;

            if (userCrudGroupOwner > 1 && serviceFields.ContainsKey("crudGroupOwner"))
            {
                int?objCrudGroupOwner = (int?)obj.GetType().GetProperty("CrudGroupOwner").GetValue(obj);

                if (objCrudGroupOwner == null)
                {
                    obj.GetType().GetProperty("CrudGroupOwner").SetValue(obj, userCrudGroupOwner);
                    objCrudGroupOwner = userCrudGroupOwner;
                }

                if (objCrudGroupOwner == userCrudGroupOwner)
                {
                    if (serviceFields.ContainsKey("crudGroup"))
                    {
                        int crudGroup = (int)obj.GetType().GetProperty("CrudGroup").GetValue(obj);

                        if (login.groups.IndexOf(crudGroup) < 0)
                        {
                            response = Response.Unauthorized("unauthorized object crudGroup");
                        }
                    }
                }
                else
                {
                    response = Response.Unauthorized("unauthorized object crudGroupOwner");
                }
            }

            return(response);
        }
Exemplo n.º 7
0
// processRequest
// main
        private ActionResult ProcessRequest(HttpContext requestContext, DbContext entityManager, String serviceName, String uriPath)
        {
// crudProcess
            Func <LoginResponse, ActionResult> crudProcess = login => {
                Type        objectClass = RequestFilter.mapClass[serviceName];
                HttpRequest uriInfo     = requestContext.Request;
                Object      obj         = null;

                if (uriPath.Equals("create") || uriPath.Equals("update"))
                {
                    try {
                        var str = new StreamReader(requestContext.Request.Body).ReadToEnd();
                        obj = JsonConvert.DeserializeObject(str, objectClass, new JsonSerializerSettings {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });
                    } catch (Exception e) {
                        return(Response.InternalServerError(e.Message));
                    }
                }

                Task <ActionResult> cf;

                if (uriPath.Equals("create"))
                {
                    cf = RequestFilter.ProcessCreate <dynamic> (login, entityManager, serviceName, obj);
                }
                else if (uriPath.Equals("update"))
                {
                    cf = RequestFilter.ProcessUpdate <dynamic> (login, uriInfo, entityManager, serviceName, obj);
                }
                else if (uriPath.Equals("delete"))
                {
                    cf = RequestFilter.ProcessDelete <dynamic> (login, uriInfo, entityManager, serviceName);
                }
                else if (uriPath.Equals("read"))
                {
                    cf = RequestFilter.ProcessRead <dynamic> (login, uriInfo, entityManager, serviceName);
                }
                else if (uriPath.Equals("query"))
                {
                    cf = RequestFilter.ProcessQuery <dynamic>(login, uriInfo, entityManager, serviceName);
                }
                else
                {
                    return(null);
                }

                cf.Wait();

                if (cf.Exception != null)
                {
                    return(Response.InternalServerError(cf.Exception.Message));
                }
                else
                {
                    return(cf.Result);
                }
            };

            Func <CrudUser, Boolean?> authorization = user => {
                Boolean?access = null;
                JObject json   = JObject.Parse(user.Roles);
                // verfica a permissao de acesso
                if (json[serviceName] != null)
                {
                    var serviceAuth = json[serviceName];

                    if (serviceAuth[uriPath] != null)
                    {
                        access = serviceAuth[uriPath].Value <Boolean?>();
                    }
                }

                return(access);
            };

            Func <ActionResult> authWithToken = () => {
                ActionResult response;
                String       authorizationHeader = requestContext.Request.Headers["Authorization"];

                if (authorizationHeader != null && authorizationHeader.StartsWith("Token "))
                {
                    String        token = authorizationHeader.Substring(6);
                    LoginResponse login = RequestFilter.logins[token];

                    if (login != null)
                    {
                        Boolean?access = authorization(login.user);

                        if (access != false)
                        {
                            ClaimsPrincipal securityContextOld = requestContext.User;

                            if (securityContextOld == null || securityContextOld.Identity == null || securityContextOld.Identity.Name == null)
                            {
                                ImplSecurityContext securityContext = new ImplSecurityContext(login);
                                requestContext.User = securityContext;

                                if (access == true)
                                {
                                    response = crudProcess(login);
                                }
                                else
                                {
                                    response = null;
                                }
                            }
                            else
                            {
                                response = Response.BadRequest("Already Identity found : " + securityContextOld.Identity.Name);
                            }
                        }
                        else
                        {
                            response = Response.Unauthorized("Explicit Unauthorized");
                        }
                    }
                    else
                    {
                        response = Response.Unauthorized("Authorization replaced by new login in another session");
                    }
                }
                else
                {
                    response = Response.Unauthorized("Authorization token header invalid");
                }

                return(response);
            };

            return(authWithToken());
        }
Exemplo n.º 8
0
 // public processRead
 static public Task <ActionResult> ProcessRead <T>(IIdentity user, HttpRequest uriInfo, DbContext entityManager, String serviceName) where T : class
 {
     return(RequestFilter.GetObject <T>(user, uriInfo, entityManager, serviceName).ContinueWith <ActionResult>(taskGet => {
         return Response.Ok(taskGet.Result);
     }, TaskContinuationOptions.NotOnFaulted));
 }