public void LoadUserAccess(int id)
        {
            if (SystemClass.CheckConnection())
            {
                ImusCityHallEntities db = new ImusCityHallEntities();
                userAccessList.Clear();
                db = new ImusCityHallEntities();
                var subModules = db.SubModules.OrderBy(m => m.Name).ToList();
                foreach (var subModule in subModules)
                {
                    bool selectedSubModule = false;
                    if (db.SubModuleUsers.Any(m => m.EmployeeID == id && m.SubModuleID == subModule.SubModuleID))
                    {
                        selectedSubModule = true;
                    }
                    UserAccessModel userAccess = new UserAccessModel()
                    {
                        Name       = subModule.Name,
                        Id         = subModule.SubModuleID,
                        IsSelected = selectedSubModule
                    };
                    userAccessList.Add(userAccess);
                }

                moduleslb.ItemsSource       = userAccessList;
                moduleslb.SelectedValuePath = "Id";
                moduleslb.Items.Refresh();
                Employee employee = db.Employees.Find(id);
                adminchk.IsChecked = employee.IsAdmin == true ? true : false;
            }
            else
            {
                MessageBox.Show(SystemClass.DBConnectionErrorMessage);
            }
        }
        private async Task <IActionResult> GetToken(ApplicationUser user)
        {
            try
            {
                var _UserClaims = await _UserManager.GetClaimsAsync(user);

                List <Claim> _Claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.NameIdentifier, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                };
                _Claims.Union(_UserClaims);

                IList <string> _Roles = await _UserManager.GetRolesAsync(user);

                foreach (var userRole in _Roles)
                {
                    _Claims.Add(new Claim(ClaimTypes.Role, userRole));
                    var role = await _RoleManager.FindByNameAsync(userRole);

                    if (role != null)
                    {
                        var roleClaims = await _RoleManager.GetClaimsAsync(role);

                        foreach (Claim roleClaim in roleClaims)
                        {
                            _Claims.Add(roleClaim);
                        }
                    }
                }
                string _TokenKey      = _Configuration["JwtSecurityToken:Key"];
                string _TokenAudience = _Configuration["JwtSecurityToken:Audience"];
                string _TokenIssuer   = _Configuration["JwtSecurityToken:Issuer"];

                var _SymmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_TokenKey));
                var _SigningCredentials   = new SigningCredentials(_SymmetricSecurityKey, SecurityAlgorithms.HmacSha256);

                var _JwtSecurityToken = new JwtSecurityToken(issuer: _TokenIssuer,
                                                             audience: _TokenAudience,
                                                             claims: _Claims,
                                                             expires: DateTime.UtcNow.AddDays(180),
                                                             signingCredentials: _SigningCredentials);

                UserAccessModel _UserAccess = new UserAccessModel(fullName: user.FullName,
                                                                  token: new JwtSecurityTokenHandler().WriteToken(_JwtSecurityToken),
                                                                  expirationDate: _JwtSecurityToken.ValidTo);
                return(Ok(_UserAccess));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        static async Task <Uri> CreateProductAsync(UserAccessModel userAccessModel)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(
                "http://localhost:9388/submit", userAccessModel);

            response.EnsureSuccessStatusCode();

            // return URI of the created resource.
            return(response.Headers.Location);
        }
        private void GetToken()
        {
            UserAccessModel userAccessModel = new UserAccessModel();

            userAccessModel.ClientId     = "b20033f1-af49-421f-81b9-5e32bc7f5149";
            userAccessModel.ClientSecret = "c993b4bf-a362-4469-b7d7-d1a39819021b";
            userAccessModel.RedirectUrl  = "http://localhost:9388/token";
            userAccessModel.ServerUrl    = "http://localhost:15536";
            var convertedModel = JsonConvert.SerializeObject(userAccessModel);

            //CreateProductAsync(userAccessModel);
            new HttpClient().PostAsync("http://localhost:9388/Submit", new StringContent(convertedModel, Encoding.UTF8, "application/json"));
        }
Beispiel #5
0
        private void UnCheck(object sender)
        {
            CheckBox chk = sender as CheckBox;

            if (chk != null)
            {
                object          item = chk.DataContext;
                UserAccessModel obj  = new UserAccessModel();
                obj = (UserAccessModel)item;

                ObservableCollection <UserAccessModel> _ListGrid_Module = new ObservableCollection <UserAccessModel>();
                // ObservableCollection<UserAccessModel> _ListGrid_Temp = new ObservableCollection<UserAccessModel>();
                var Load_Item = (((IEnumerable)App.Current.Properties["DataGrid"]).Cast <UserAccessModel>()).ToList();

                foreach (var item2 in Load_Item)
                {
                    if (item2.MODULE_ID == obj.MODULE_ID)
                    {
                        _ListGrid_Module.Add(new UserAccessModel
                        {
                            ACTION_CREATE = obj.ACTION_CREATE,
                            EDIT          = obj.EDIT,
                            ACTION_VIEW   = obj.ACTION_VIEW,
                            ACTION_DELETE = obj.ACTION_DELETE,
                            MODULE_ID     = obj.MODULE_ID,
                            Company_Id    = item2.Company_Id,
                            User_Id       = Convert.ToInt64(App.Current.Properties["EmpId"].ToString())
                        });
                    }
                    else
                    {
                        _ListGrid_Module.Add(new UserAccessModel
                        {
                            ACTION_CREATE = item2.ACTION_CREATE,
                            EDIT          = item2.EDIT,
                            ACTION_VIEW   = item2.ACTION_VIEW,
                            ACTION_DELETE = item2.ACTION_DELETE,
                            MODULE_ID     = item2.MODULE_ID,
                            Company_Id    = item2.Company_Id,
                            User_Id       = Convert.ToInt64(App.Current.Properties["EmpId"].ToString())
                        });
                    }


                    _Access_Temp = _ListGrid_Module;

                    App.Current.Properties["DataGrid"] = _ListGrid_Module;
                }
            }
        }
Beispiel #6
0
        public ActionResult GrantUserAccessToProject(ProjectUserAccessViewModel model)
        {
            if (model.UserId != null && !model.UserId.Equals(""))
            {
                UserAccessModel userAccessModel = new UserAccessModel()
                {
                    Id        = model.Id,
                    ProjectId = model.ProjectId,
                    UserId    = model.UserId
                };
                _dataManager.AddUserAccessToProject(userAccessModel);
                _dataManager.SaveChanges();
            }

            return(RedirectToAction("EditProjectAccess", "Projects", new { Id = model.ProjectId }));
        }
Beispiel #7
0
        //TODO: it is recommended to have an [Authorize] attribute set
        public ActionResult Submit([FromBody] UserAccessModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var nopAuthorizationManager = new AuthorizationManager(model.ClientId, model.ClientSecret, model.ServerUrl);

                    var redirectUrl = Url.RouteUrl("GetAccessToken", null, HttpContext.Request.Scheme); //  "http://localhost:9388/token";

                    if (redirectUrl != model.RedirectUrl)
                    {
                        return(BadRequest());
                    }

                    var convertedId          = JsonConvert.SerializeObject(model.ClientId);
                    var convertedSecret      = JsonConvert.SerializeObject(model.ClientSecret);
                    var convertedServerUrl   = JsonConvert.SerializeObject(model.ServerUrl);
                    var convertedredirectUrl = JsonConvert.SerializeObject(redirectUrl);
                    //var convertedstate = JsonConvert.SerializeObject(state);

                    // For demo purposes this data is kept into the current Session, but in production environment you should keep it in your database
                    HttpContext.Session.SetString("clientId", model.ClientId);
                    HttpContext.Session.SetString("clientSecret", model.ClientSecret);
                    HttpContext.Session.SetString("serverUrl", model.ServerUrl);
                    HttpContext.Session.SetString("redirectUrl", model.RedirectUrl);

                    // This should not be saved anywhere.
                    var state = Guid.NewGuid();
                    // var convertedstate = JsonConvert.SerializeObject(state);
                    HttpContext.Session.SetString("state", state.ToString());

                    string authUrl = nopAuthorizationManager.BuildAuthUrl(redirectUrl, new string[] { }, state.ToString());

                    return(Redirect(authUrl));
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.Message));
                }
            }

            return(BadRequest());
        }
Beispiel #8
0
        public static UserAccessModel GetUserAccess(string upn)
        {
            var result = new UserAccessModel();
            var user   = SQLAdapter.GetUserByUPN(upn);

            if (user == null)
            {
                throw new Exception("User " + upn + " does not exist");
            }

            result.IsGlobalAdmin = user.IsGlobalAdmin == true;

            var userRoleMappings = SQLAdapter.GetUsersByUPN(upn);

            result.IsLecturer     = userRoleMappings.Any(m => m.Role.Name == Constants.LECTURER_ROLE);
            result.IsDemonstrator = userRoleMappings.Any(m => m.Role.Name == Constants.DEMONSTRATOR_ROLE);

            return(result);
        }
        //TODO: it is recommended to have an [Authorize] attribute set
        public ActionResult Submit(UserAccessModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var nopAuthorizationManager = new AuthorizationManager(model.ClientId, model.ClientSecret, model.ServerUrl);

                    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Url.Scheme);

                    if (redirectUrl != model.RedirectUrl)
                    {
                        return(BadRequest());
                    }

                    // For demo purposes this data is kept into the current Session, but in production environment you should keep it in your database
                    Session["clientId"]     = model.ClientId;
                    Session["clientSecret"] = model.ClientSecret;
                    Session["serverUrl"]    = model.ServerUrl;
                    Session["redirectUrl"]  = redirectUrl;

                    // This should not be saved anywhere.
                    var state = Guid.NewGuid();
                    Session["state"] = state;

                    string authUrl = nopAuthorizationManager.BuildAuthUrl(redirectUrl, new string[] { }, state.ToString());

                    return(Redirect(authUrl));
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.Message));
                }
            }

            return(BadRequest());
        }
        public ActionResult Submit(UserAccessModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var authorizationManager = new AuthorizationManager(model.ClientId, model.ClientSecret, model.ServerUrl);

                    var redirectUrl = Url.RouteUrl("GetAccessToken", null, Request.Url.Scheme);

                    if (redirectUrl != model.RedirectUrl)
                    {
                        return(BadRequest());
                    }

                    Session["clientId"]     = model.ClientId;
                    Session["clientSecret"] = model.ClientSecret;
                    Session["serverUrl"]    = model.ServerUrl;
                    Session["redirectUrl"]  = redirectUrl;

                    // This should not be saved anywhere.
                    var state = Guid.NewGuid();
                    Session["state"] = state;

                    string authUrl = authorizationManager.BuildAuthUrl(redirectUrl, new string[] { "sms_api" }, state.ToString());

                    return(Redirect(authUrl));
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.Message));
                }
            }

            return(BadRequest());
        }
 public List<UserAccessModel> GetAllUserAccessName()
 {
     List<UserAccessModel> userAccessModels = new List<UserAccessModel>();
     string query = String.Format("Select * from tblUserAccess");
        // sqlCommand.CommandText = query;
     using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString))
     {
         SqlCommand cmd = new SqlCommand(query,con3);
         con3.Open();
         SqlDataReader rdr = cmd.ExecuteReader();
         while (rdr.Read())
         {
             UserAccessModel userAccessModel = new UserAccessModel();
             userAccessModel.ID = Convert.ToInt32(rdr[0]);
             userAccessModel.UserAccessName = rdr[1].ToString();
             userAccessModels.Add(userAccessModel);
         }
         con3.Close();
     }
     return userAccessModels;
 }
        protected void updateButton_Click(object sender, EventArgs e)
        {
            if (userAccessDropDownlist.SelectedValue == "-1")
            {
                statusLabel.Text = "Please select user access name";
            }
            else
            {
                UserAccessModel userAccessModel = new UserAccessModel();
                userAccessModel.ID = Convert.ToInt32(userAccessDropDownlist.SelectedValue);
                if (userAccessTextBox.Text=="")
                {
                    statusLabel.Text = "Please enter the value in the textbox.";
                }
                else
                {
                    userAccessModel.UserAccessName = userAccessTextBox.Text;
                }

                if (UpdateSelectedUserAccessNameAndGetId(userAccessModel) > 0)
                {
                    int rowsUpdated = 0;
                    int userAccessId = UpdateSelectedUserAccessNameAndGetId(userAccessModel);
                    string query = String.Format("Update tblUserRoll set RollStatus=@rollStatus where UserRollValue=@userRollValue and UserAccessNameId=@userAccessId");
                    using (SqlConnection con8 = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString))
                    {
                        SqlCommand cmd8 = new SqlCommand(query,con8);
                        con8.Open();
                        foreach (ListItem item in perDealershipOverridesCheckBoxList.Items)
                        {
                            cmd8.Parameters.Clear();
                            if (item.Selected)
                            {
                                cmd8.Parameters.AddWithValue("@rollStatus","True");
                            }
                            else
                            {
                                cmd8.Parameters.AddWithValue("@rollStatus","False");
                            }

                            cmd8.Parameters.AddWithValue("@userRollValue",item.Value);
                            cmd8.Parameters.AddWithValue("@userAccessId", userAccessId);
                            rowsUpdated = cmd8.ExecuteNonQuery();

                        }
                        foreach (ListItem item in globalRulesCheckBoxList.Items)
                        {
                            cmd8.Parameters.Clear();

                            if (item.Selected)
                            {
                                cmd8.Parameters.AddWithValue("@rollStatus", "True");
                            }
                            else
                            {
                                cmd8.Parameters.AddWithValue("@rollStatus", "False");
                            }

                            cmd8.Parameters.AddWithValue("@userRollValue", item.Value);
                            cmd8.Parameters.AddWithValue("@userAccessId", userAccessId);
                            rowsUpdated= cmd8.ExecuteNonQuery();

                        }

                        con8.Close();
                        if (rowsUpdated>0)
                        {
                            statusLabel.ForeColor = System.Drawing.Color.Green;
                            statusLabel.Text = "Updated.";
                            DeSelectItemInCheckBoxList();
                            GetAllUserAccessNameInDropdownList();
                            ListItem li = new ListItem("Select user access", "-1");
                            userAccessDropDownlist.Items.Insert(0, li);
                            userAccessTextBox.Text = "";

                        }
                        else
                        {
                            statusLabel.Text = "Not Updated.";
                        }
                    }

                }
            }
        }
        protected void createButton_Click(object sender, EventArgs e)
        {
            int lastIdentityOfUserAccess = 0;
            UserAccessModel userAccessModel = new UserAccessModel();
            userAccessModel.UserAccessName = userAccessTextBox.Text;
            if (userAccessTextBox.Text=="")
            {
                statusLabel.Text = "Please enter the name";
            }
            else
            {
                if (IsUserAccessNameExist(userAccessTextBox.Text))
                {
                    statusLabel.Text = "This user access name already exist. Try with another name.";
                }
                else
                {
                    if (SaveUserAccessName(userAccessModel) > 0)
                    {
                        lastIdentityOfUserAccess = GetLastIdentityOfUserAccess();

                        foreach (ListItem item in perDealershipOverridesCheckBoxList.Items)
                        {
                            UserRollModel userRollModel = new UserRollModel();
                            userRollModel.RollValue = item.Value;
                            if (item.Selected)
                            {
                                userRollModel.Status = "True";
                            }
                            else
                            {
                                userRollModel.Status = "False";
                            }
                            userRollModel.AccessRollId = lastIdentityOfUserAccess;
                            if (SaveUserRolls(userRollModel) > 0)
                            {
                                statusLabel.ForeColor = System.Drawing.Color.Green;
                                statusLabel.Text = "User rolls saved.";
                                GetAllUserAccessNameInDropdownList();
                                ListItem li = new ListItem("Select user access", "-1");
                                userAccessDropDownlist.Items.Insert(0, li);
                            }
                            else
                            {
                                statusLabel.Text = "User rolls not saved.";
                                GetAllUserAccessNameInDropdownList();
                                ListItem li = new ListItem("Select user access", "-1");
                                userAccessDropDownlist.Items.Insert(0, li);
                            }
                        }
                        foreach (ListItem item in globalRulesCheckBoxList.Items)
                        {
                            UserRollModel userRollModel = new UserRollModel();
                            userRollModel.RollValue = item.Value;
                            if (item.Selected)
                            {
                                userRollModel.Status = "True";
                            }
                            else
                            {
                                userRollModel.Status = "False";
                            }
                            userRollModel.AccessRollId = lastIdentityOfUserAccess;
                            if (SaveUserRolls(userRollModel) > 0)
                            {
                                statusLabel.ForeColor = System.Drawing.Color.Green;
                                statusLabel.Text = "User rolls saved.";
                                GetAllUserAccessNameInDropdownList();
                                ListItem li = new ListItem("Select user access", "-1");
                                userAccessDropDownlist.Items.Insert(0, li);

                            }
                            else
                            {
                                statusLabel.Text = "User rolls not saved.";
                                GetAllUserAccessNameInDropdownList();
                                ListItem li = new ListItem("Select user access", "-1");
                                userAccessDropDownlist.Items.Insert(0, li);
                            }

                        }
                        DeSelectItemInCheckBoxList();
                    }
                    else
                    {
                        statusLabel.Text = "User Access not saved.";
                    }
                }
            }
        }
        public int UpdateSelectedUserAccessNameAndGetId(UserAccessModel userAccessModel)
        {
            int updatedId = 0;
            string query = String.Format("Update tblUserAccess set UserAccessName='{0}' output inserted.ID where ID='{1}'", userAccessModel.UserAccessName,userAccessModel.ID);

            using (SqlConnection con5 = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString))
            {
                SqlCommand cmd5 = new SqlCommand(query,con5);
                con5.Open();
                updatedId = Convert.ToInt32(cmd5.ExecuteScalar());
                con5.Close();
            }
            return updatedId;
        }
        public int SaveUserAccessName(UserAccessModel userAccessModel)
        {
            int rowsInserted = 0;
            string query = String.Format("Insert into tblUserAccess values('{0}')",userAccessModel.UserAccessName);

            using (SqlConnection con4 = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ConnectionString))
            {
                SqlCommand cmd4 = new SqlCommand(query,con4);
                con4.Open();
                rowsInserted = cmd4.ExecuteNonQuery();
                con4.Close();
            }
            return rowsInserted;
        }
Beispiel #16
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (Appsettings.App("Middleware", "RecordAccessLogs", "Enabled").ToBoolReq())
            {
                var api        = context.Request.Path.ToString().TrimEnd('/').ToLower();
                var ignoreApis = Appsettings.App("Middleware", "RecordAccessLogs", "IgnoreApis"); //忽略的接口

                // 过滤,只有接口
                if (api.Contains("api") && !ignoreApis.Contains(api))
                {
                    _stopwatch.Restart();

                    HttpRequest request = context.Request;

                    UserAccessModel userAccessModel = new UserAccessModel();

                    userAccessModel.User          = _user.Name;
                    userAccessModel.ClientIP      = IPLogMildd.GetClientIP(context)?.Replace("::ffff:", "");
                    userAccessModel.ServiceIP     = context.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.Connection.LocalPort;
                    userAccessModel.Url           = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + context.Request.Path;
                    userAccessModel.BeginTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    userAccessModel.RequestMethod = request.Method;
                    userAccessModel.Agent         = request.Headers["User-Agent"].ToString();

                    // 获取请求body内容
                    if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put"))
                    {
                        // 启用倒带功能,就可以让 Request.Body 可以再次读取
                        request.EnableBuffering();

                        Stream stream = request.Body;
                        byte[] buffer = new byte[request.ContentLength.Value];
                        stream.Read(buffer, 0, buffer.Length);
                        userAccessModel.RequestData = Encoding.UTF8.GetString(buffer);

                        request.Body.Position = 0;
                    }
                    else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete"))
                    {
                        userAccessModel.RequestData = HttpUtility.UrlDecode(request.QueryString.ToString(), Encoding.UTF8);
                    }

                    // 获取Response.Body内容
                    var originalBodyStream = context.Response.Body;
                    using (var responseBody = new MemoryStream())
                    {
                        context.Response.Body = responseBody;

                        await _next(context);

                        var responseBodyData = await GetResponse(context.Response);

                        await responseBody.CopyToAsync(originalBodyStream);
                    }

                    // 响应完成记录时间和存入日志
                    context.Response.OnCompleted(() =>
                    {
                        _stopwatch.Stop();

                        userAccessModel.OPTime = _stopwatch.ElapsedMilliseconds + "ms";

                        // 自定义log输出
                        var requestInfo = JsonConvert.SerializeObject(userAccessModel);
                        //Parallel.For(0, 1, e =>
                        //{
                        //    LogLock.OutSql2Log("RecordAccessLogs", new string[] { requestInfo + "," }, false);
                        //});
                        SerilogServer.WriteLog("RecordAccessLogs", new string[] { requestInfo + ", " }, false);

                        return(Task.CompletedTask);
                    });
                }
                else
                {
                    await _next(context);
                }
            }
            else
            {
                await _next(context);
            }
        }