Пример #1
0
        public IActionResult Post([FromBody] SystemUserModel model)
        {
            try
            {
                if (!string.IsNullOrEmpty(model.Id))
                {
                    //Check Empty Guid
                    Guid userid = new Guid(model.Id);
                    if (userid != Guid.Empty)
                    {
                        //Update
                        APIReturnModel update = SystemUserService.UpdateSystemUsers(model);
                        return(Ok(new { data = update.Value, status = StatusMessages.Get(update.Status) }));
                    }
                    else
                    {
                        //Passed User ID is empty guid
                        return(Ok(new { data = string.Empty, status = StatusMessages.Error_UserUpdateFailed_GUID }));
                    }
                }
                else
                {
                    //Insert
                    APIReturnModel create = SystemUserService.CreateSystemUsers(model);
                    return(Ok(new { data = create.Value, status = StatusMessages.Get(create.Status) }));
                }
            }
            catch
            {
            }

            return(Ok(new { data = string.Empty, status = StatusMessages.Error_Failed }));
        }
Пример #2
0
        public async Task <IActionResult> Get(string id)
        {
            try
            {
                if (!Guid.TryParse(id, out Guid isGuid))
                {
                    throw new GuidNotValidException();
                }

                var systemUser = await _systemUserService.GetItem(new Guid(id));

                var model = new SystemUserModel(systemUser);

                responseModels.Add("SystemUser", model);
                response = new ApiResponse(HttpStatusCode.OK, "System user found.", responseModels);
                return(Ok(new { response }));
            }
            catch (GuidNotValidException exception)
            {
                response = new ApiResponse(HttpStatusCode.BadRequest, null, exception, null);
                return(Ok(new { response }));
            }
            catch (UserNotFoundException exception)
            {
                response = new ApiResponse(HttpStatusCode.NotFound, null, exception, null);
                return(Ok(new { response }));
            }
            catch (Exception exception)
            {
                response = new ApiResponse(HttpStatusCode.BadRequest, null, exception, null);
                return(Ok(new { response }));
            }
        }
Пример #3
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string operationName = "Operation name"; //It is for example
            string moduleName    = "Module name";    //It is for example

            try
            {
                //Obtain session user
                user = (SystemUserModel)HttpContext.Current.Session["SystemUser"];
                if (!user.canModifyPromoUsers())
                {
                    filterContext.Result = new RedirectResult("~/Error/UnauthorizedOperation?operation=" +
                                                              operationName +
                                                              "&modulo=" +
                                                              moduleName
                                                              );
                }
            }
            catch (Exception error)
            {
                filterContext.Result = new RedirectResult("~/Error/UnauthorizedOperation?operation=" +
                                                          operationName +
                                                          "&module=" +
                                                          moduleName +
                                                          "&msgErrorExcepcion=" +
                                                          error.Message
                                                          );
            }
        }
        public override int deleteUser(BaseUserModel baseUser)
        {
            SystemUserModel user         = (SystemUserModel)baseUser;
            int             affectedRows = factory.Query(ASSOCIATED_TABLE_NAME).Where("email", "=", user.email).Delete();

            return(affectedRows);
        }
Пример #5
0
        public MainAdminViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher, SystemUserDTO mainAdmin)
            : base(userInterop, controllerInterop, dispatcher)
        {
            originalEntity = mainAdmin;

            Model = new SystemUserModel(mainAdmin);
            Model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ModelPropertyChanged);
        }
Пример #6
0
        public MainAdminViewModel(IUserInterop userInterop, IControllerInterop controllerInterop, Dispatcher dispatcher)
            : base(userInterop, controllerInterop, dispatcher)
        {
            originalEntity = new SystemUserDTO();

            Model = new SystemUserModel(originalEntity as SystemUserDTO) { Role = UserRoles.MainAdmin };
            this.Model.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ModelPropertyChanged);
        }
Пример #7
0
        public JsonResult AddSystemUser(SystemUserModel model)
        {
            JsonResult json = new JsonResult();

            try
            {
                var  result = UserManager.FindByNameAsync(model.Mobile).Result;
                bool exist  = result != null;
                if (exist)
                {
                    json.Data = new { status = 0, message = "该手机号码已经存在" };
                    return(json);
                }

                if (ModelState.IsValid)
                {
                    var       id      = Guid.NewGuid().ToString();
                    AdminUser regInfo = new AdminUser()
                    {
                        AccessFailedCount = 0,
                        CreationDate      = DateTime.Now,
                        CreatorUserId     = CurUser.UserId,
                        PhoneNumber       = model.Mobile,
                        Type                 = model.RoleType,
                        UpdateDate           = DateTime.Now,
                        UpdatorUserId        = CurUser.UserId,
                        UserName             = model.Mobile,
                        PasswordHash         = new PasswordHasher().HashPassword(model.Password),
                        Name                 = model.RealName,
                        IsEnable             = true,
                        Email                = "*****@*****.**",
                        Id                   = id,
                        SecurityStamp        = Guid.NewGuid().ToString(),
                        LockoutEnabled       = false,
                        PhoneNumberConfirmed = true
                    };
                    var count = UserManager.AddUserAndUserRole(regInfo, model.RoleId);
                    if (count > 0)
                    {
                        json.Data = new { status = 1, message = "成功添加用户" };
                    }
                    else
                    {
                        json.Data = new { status = 2, message = "添加用户失败" };
                    }
                }
                else
                {
                    json.Data = new { status = 0, message = "字段为按要求填写" };
                }
            }
            catch (Exception ex)
            {
                logger.Error("AddSystemUser", ex);
                json.Data = new { status = 0, message = "服务端出错" };
            }
            return(json);
        }
Пример #8
0
        private bool ValidateImageUploaded(SystemUserModel model, bool createMode = true)
        {
            model.PhotoLocationUpload = (model.PhotoLocationUpload ?? Request.Files["PhotoLocationUpload"]);
            if (model.PhotoLocationUpload != null && model.PhotoLocationUpload.ContentLength > 0)
            {
                var fileExtension = Path.GetExtension(model.PhotoLocationUpload.FileName).TrimStart(new[] { '.' });
                if (!SettingsHelper <CommonSettings> .Settings.AllowedImageExtensions.Any(p => p.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase)))
                {
                    ModelState.AddModelError("PhotoLocationUpload", Resources.GoodsReceivedNoteController_String_FileExtensionNotSupported);
                }
                else
                {
                    if (model.PhotoLocationUpload.ContentLength >
                        SettingsHelper <CommonSettings> .Settings.PersonPhotoMaxSize * 1024)
                    {
                        ModelState.AddModelError("PhotoLocationUpload",
                                                 Resources.GoodsReceivedNoteController_String_ImageSizeMsg.F(
                                                     SettingsHelper <CommonSettings> .Settings.PersonPhotoMaxSize * 1024,
                                                     model.PhotoLocationUpload.ContentLength));
                    }
                    else if (!m_ImageService.IsImage(model.PhotoLocationUpload.InputStream))
                    {
                        ModelState.AddModelError("PhotoLocationUpload", Resources.GoodsReceivedNoteController_String_FileUploadedNotValid);
                    }
                }

                model.PhotoLocationUpload.InputStream.Seek(0, SeekOrigin.Begin);
            }

            model.SignatureImageUpload = (model.SignatureImageUpload ?? Request.Files["SignatureImageUpload"]);
            if (model.SignatureImageUpload != null && model.SignatureImageUpload.ContentLength > 0)
            {
                var fileExtension = Path.GetExtension(model.SignatureImageUpload.FileName).TrimStart(new[] { '.' });
                if (!SettingsHelper <CommonSettings> .Settings.AllowedImageExtensions.Any(p => p.Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase)))
                {
                    ModelState.AddModelError("SignatureImageUpload", Resources.GoodsReceivedNoteController_String_FileExtensionNotSupported);
                }
                else
                {
                    if (model.SignatureImageUpload.ContentLength >
                        SettingsHelper <CommonSettings> .Settings.SignaturePhotoMaxSize * 1024)
                    {
                        ModelState.AddModelError("SignatureImageUpload",
                                                 Resources.GoodsReceivedNoteController_String_ImageSizeMsg.F(
                                                     SettingsHelper <CommonSettings> .Settings.SignaturePhotoMaxSize * 1024,
                                                     model.SignatureImageUpload.ContentLength));
                    }
                    else if (!m_ImageService.IsImage(model.SignatureImageUpload.InputStream))
                    {
                        ModelState.AddModelError("SignatureImageUpload", Resources.GoodsReceivedNoteController_String_FileExtensionNotSupported);
                    }
                }

                model.SignatureImageUpload.InputStream.Seek(0, SeekOrigin.Begin);
            }

            return(ModelState.IsValid);
        }
        public int changeRoleToUser(SystemUserModel user)
        {
            int affectedRows = factory.Query(ASSOCIATED_TABLE_NAME).Where("email", "=", user.email).Update(new
            {
                role = user.role
            });

            return(affectedRows);
        }
Пример #10
0
        public System.Web.Http.Results.OkNegotiatedContentResult <SystemUserModel> GetUserRole([FromBody] LoginIdModel loginIdModel)
        {
            try
            {
                SqlDataReader reader       = null;
                SqlConnection myConnection = new SqlConnection();
                myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"];
                SqlCommand sqlCmd = new SqlCommand();

                sqlCmd.CommandText = "spGetUserRole";
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Connection  = myConnection;

                SqlParameter parameter = new SqlParameter();
                parameter.ParameterName = "@Login_Id";
                parameter.SqlDbType     = SqlDbType.VarChar;
                parameter.Direction     = ParameterDirection.Input;
                parameter.Size          = 50;
                parameter.Value         = loginIdModel.LoginId;
                sqlCmd.Parameters.Add(parameter);

                myConnection.Open();
                reader = sqlCmd.ExecuteReader();

                int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id");
                int firstNameOrdinal    = reader.GetOrdinal("First_Name");
                int lastNameOrdinal     = reader.GetOrdinal("Last_Name");
                int emailAddressOrdinal = reader.GetOrdinal("Email_Address");
                int loginIdOrdinal      = reader.GetOrdinal("Login_Id");
                int roleOrdinal         = reader.GetOrdinal("Role");
                int endDateOrdinal      = reader.GetOrdinal("End_Date");

                SystemUserModel systemUserModel = new SystemUserModel();

                if (reader.Read())
                {
                    systemUserModel.SystemUserId = reader.GetInt32(systemUserIdOrdinal);
                    systemUserModel.FirstName    = reader.GetString(firstNameOrdinal);
                    systemUserModel.LastName     = reader.GetString(lastNameOrdinal);
                    systemUserModel.EmailAddress = reader.GetString(emailAddressOrdinal);
                    systemUserModel.LoginId      = reader.GetString(loginIdOrdinal);
                    systemUserModel.Role         = reader.GetString(roleOrdinal);
                    systemUserModel.EndDate      = (reader.IsDBNull(endDateOrdinal) ? (DateTime?)null : (DateTime?)reader.GetDateTime(endDateOrdinal));
                }

                myConnection.Close();

                return(Ok(content: systemUserModel));
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return(null);
            }
        }
        public SystemUserModel getSystemUser(SystemUserModel externalUser)
        {
            SystemUserModel systemUser = factory.
                                         Query(ASSOCIATED_TABLE_NAME).
                                         Select("*").
                                         Where("email", "=", externalUser.email).
                                         Where("password", "=", Encryptor.GetSHA256(externalUser.password)).
                                         FirstOrDefault <SystemUserModel>();

            return(systemUser);
        }
Пример #12
0
        public ActionResult Profile(SystemUserModel model)
        {
            ValidateImageUploaded(model, false);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = m_SystemUserService.GetUserById(m_UserContext.CurrentUser.Id, false);

            if (user == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (user.Staff != null && user.Staff.Person != null && user.Staff.Person.OfficialEmail != model.Email)
            {
                var emailUser = m_SystemUserService.FindUsers(new UserFilter {
                    Email = model.Email
                }, 0, 1).FirstOrDefault();
                if (emailUser != null)
                {
                    ModelState.AddModelError("", Resources.PersonController_String_EmailAlreadyInUse.F(model.Email));
                    return(View(model));
                }
            }

            try
            {
                using (var transactionScope = new TransactionScope())
                {
                    var person = m_PersonService.GetPersonById(user.Staff.Person.Id);
                    person = model.ToEntity(person);
                    SaveImages(person, model);
                    m_PersonService.UpdatePerson(person);

                    if (model.Password.IsNotNullOrWhiteSpace())
                    {
                        m_SystemUserService.ChangePassword(new ChangePasswordRequest(model.Email, true, model.Password, model.OldPassword));
                    }

                    transactionScope.Complete();

                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
            }

            return(View(model));
        }
Пример #13
0
        public bool isPossibleReturnPromoUsersInfo(LoginValuesModel loginValues)
        {
            bool            response            = false;
            SystemUserModel retrievedUserFromDB = getUserFromDB(loginValues);

            if (isValidUser(retrievedUserFromDB))
            {
                response = retrievedUserFromDB.canVisualizePromoUsers();
            }
            return(response);
        }
Пример #14
0
        public ActionResult Create()
        {
            if (!m_PermissionService.Authorize(StandardPermissionProvider.SystemUsersManage))
            {
                return(AccessDeniedView());
            }
            var model = new SystemUserModel();

            PrepareSystemUserModel(model);
            return(View(model));
        }
Пример #15
0
        public async Task <IActionResult> Update(SystemUserModel model)
        {
            try
            {
                await _systemUserService.UpdateItem(model);

                response = new ApiResponse(HttpStatusCode.OK, "System user updated successfully.", null);
                return(Ok(new { response }));
            }
            catch (Exception exception)
            {
                return(BadRequest("System user update failed. Error: " + exception.Message));
            }
        }
        public async Task <SystemUserModel> UpdateItem(SystemUserModel model)
        {
            var systemAuthenticateUser = await GetItem(new Guid(model.Id));

            if (systemAuthenticateUser == null)
            {
                throw new UserNotFoundException();
            }

            systemAuthenticateUser = new SystemAuthenticateUser(model, systemAuthenticateUser);
            await _systemUsersManager.UpsertItemAsync(systemAuthenticateUser);

            return(new SystemUserModel(systemAuthenticateUser));
        }
        public async Task <ActionResult <VerityResult> > UpdateUser(SystemUserModel InputModel)
        {
            VerityResult responseResult = new VerityResult();

            try
            {
                responseResult = await _systemUserManager.CreateOrUpdateUser(InputModel, "Sys");
            }
            catch (Exception ex)
            {
                responseResult.StatusCode = HttpStatusCode.InternalServerError;
                responseResult.Message    = JsonConvert.SerializeObject(ex.Message);
            }
            return(responseResult);
        }
        public override int insertUser(BaseUserModel baseUser)
        {
            SystemUserModel user         = (SystemUserModel)baseUser;
            int             affectedRows = factory.Query(ASSOCIATED_TABLE_NAME).Insert(new
            {
                user.firstName,
                user.lastName,
                user.cellPhoneNumber,
                user.entryDate,
                user.email,
                password = Encryptor.GetSHA256(user.password),
                user.role
            });

            return(affectedRows);
        }
Пример #19
0
        private void PrepareSystemUserModel(SystemUserModel model)
        {
            var roles = m_SystemUserService.GetAllRoles(false);

            if (model.Id.IsNotEmpty())
            {
                var userRoles = m_SystemUserService.GetUserRoles(model.Id, false);
                if (userRoles.IsNotNullOrEmpty())
                {
                    model.SelectedRoleIds = userRoles.Select(p => p.RoleId).ToArray();
                }
            }

            if (roles.IsNotNullOrEmpty())
            {
                roles.ForEach(p => model.AvailableRoles.Add(new SelectListItem {
                    Text = p.Name, Value = p.Id.ToString(), Selected = model.SelectedRoleIds.IsNotNullOrEmpty() && model.SelectedRoleIds.Contains(p.Id)
                }));
            }

            var availableDesignations = m_DesignationService.GetDesignations(countryProg.Id);

            if (availableDesignations.IsNotNullOrEmpty())
            {
                availableDesignations.ForEach(p => model.AvailableDesignation.Add(new SelectListItem {
                    Text = p.Name, Value = p.Id.ToString(), Selected = model.SelectedDesignationId == p.Id
                }));
            }

            var availableCountrySuboffices = m_CountrySubOfficeService.GetCountrySubOffices1(countryProg.Id);

            if (availableCountrySuboffices.IsNotNullOrEmpty())
            {
                availableCountrySuboffices.OrderBy(p => p.countryProgramme.ProgrammeName)
                .ForEach(p => model.AvailableCountrySubOffices.Add(new SelectListItem
                {
                    Text     = p.countrySubOffice.Name,
                    Value    = p.countrySubOffice.Id.ToString(),
                    Selected = p.countrySubOffice.Id == model.SelectedCountrySubOfficeId
                }));
            }

            var financeLimits = m_budgetService.GetFinanceLimits(countryProg.Id);

            model.Password      = "";
            model.FinanceLimits = new SelectList(financeLimits, "Id", "Name");
        }
Пример #20
0
        private Int32 GetSystemUserIdFromLogin(String loginId)
        {
            SystemUserModel systemUserModel = new SystemUserModel();


            try
            {
                SqlDataReader reader       = null;
                Int32         systemUserId = 0;
                SqlConnection myConnection = new SqlConnection();
                myConnection.ConnectionString = System.Configuration.ConfigurationManager.AppSettings["DBConnection"];

                SqlCommand sqlCmd = new SqlCommand();
                sqlCmd             = new SqlCommand();
                sqlCmd.CommandText = "spGetSystemUserIdFromLogin";
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Connection  = myConnection;

                SqlParameter parameter = new SqlParameter();
                parameter.ParameterName = "@Login_Id";
                parameter.SqlDbType     = SqlDbType.VarChar;
                parameter.Direction     = ParameterDirection.Input;
                parameter.Size          = 50;
                parameter.Value         = loginId;
                sqlCmd.Parameters.Add(parameter);

                myConnection.Open();
                reader = sqlCmd.ExecuteReader();

                int systemUserIdOrdinal = reader.GetOrdinal("System_User_Id");

                if (reader.Read())
                {
                    systemUserId = reader.GetInt32(systemUserIdOrdinal);
                }

                myConnection.Close();

                return(systemUserId);
            }
            catch (Exception ex)
            {
                ExceptionModel.SaveException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString(), System.Reflection.MethodInfo.GetCurrentMethod().Name);
                return(-1);
            }
        }
Пример #21
0
        /// <summary>
        /// 1= Success, 0= Failed, 2= Username Exists, 3= Email Exists, 4= User not Found
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public APIReturnModel UpdateSystemUsers(SystemUserModel model)
        {
            try
            {
                if (IsUserNameExists(model.Username))
                {
                    return(new APIReturnModel {
                        Status = 2
                    });
                }
                if (IsEmailExists(model.Email))
                {
                    return(new APIReturnModel {
                        Status = 3
                    });
                }

                Guid       userid      = new Guid(model.Id);
                SystemUser userdetails = Db.SystemUsers.FirstOrDefault(d => d.Id == model.Id);
                if (userdetails != null)
                {
                    userdetails.Address   = model.Address;
                    userdetails.Email     = model.Email;
                    userdetails.FirstName = model.FirstName;
                    userdetails.LastName  = model.LastName;
                    userdetails.Phone     = model.Phone;
                    Db.SaveChanges();

                    return(new APIReturnModel {
                        Status = 1, Value = model.Id
                    });
                }
                else
                {
                    return new APIReturnModel {
                               Status = 4
                    }
                };
            }
            catch
            {
                return(new APIReturnModel {
                    Status = 0
                });
            }
        }
        public override int updateUser(BaseUserModel baseUser)
        {
            SystemUserModel user = (SystemUserModel)baseUser;

            user.password = Encryptor.GetSHA256(user.password);
            int affectedRows = factory.Query(ASSOCIATED_TABLE_NAME).Where("email", "=", user.email).Update(new
            {
                firstName       = user.firstName,
                lastName        = user.lastName,
                cellPhoneNumber = user.cellPhoneNumber,
                entryDate       = user.entryDate,
                password        = user.password,
                role            = user.role
            });

            return(affectedRows);
        }
 public SystemUser(SystemUserModel model)
 {
     Id              = string.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;
     NamePrefix      = model.NamePrefix;
     NameFirst       = model.NameFirst;
     NameLast        = model.NameLast;
     NameSuffix      = model.NameSuffix;
     DisplayAs       = model.DisplayAs;
     ProfileImageUrl = model.ProfileImageUrl;
     MustChangePasswordAtNextLogin = model.MustChangePasswordAtNextLogin;
     PasswordExpirationDateTime    = model.PasswordExpirationDateTime;
     Enabled              = model.Enabled;
     EmailAddresses       = SystemEmailAddress.Construct(model.EmailAddresses);
     PhoneNumbers         = SystemPhoneNumber.Construct(model.PhoneNumbers);
     Roles                = model.Roles;
     CloneToAdminDatabase = model.CloneToAdminDatabase;
 }
Пример #24
0
        public JsonResult UpdateSystemUser(SystemUserModel model)
        {
            CommonResult r = new CommonResult();

            try
            {
                if (ModelState.IsValid)
                {
                    AdminUserDto userInfo = new AdminUserDto()
                    {
                        IsEnable = model.Enabled,
                        Mobile   = model.Mobile,
                        Password = new PasswordHasher().HashPassword(model.Password),
                        Name     = model.RealName,
                        RoleIds  = new List <string>()
                        {
                            model.RoleId
                        },
                        Id = model.UserId
                    };
                    int acount = UserManager.UpdateUserAndUserRole(userInfo);
                    if (acount > 0)
                    {
                        r.message = "保存成功";
                        r.code    = (int)ResultCodeEnum.OK;
                    }
                    else
                    {
                        r.message = "保存失败";
                        r.code    = (int)ResultCodeEnum.SystemError;
                    }
                }
                else
                {
                    r.message = "字段为按要求填写";
                    r.code    = (int)ResultCodeEnum.VerifyError;
                }
            }
            catch (Exception ex)
            {
                r.message = ex.Message;
                r.code    = (int)ResultCodeEnum.SystemError;
            }
            return(Json(r));
        }
Пример #25
0
 /// <summary>
 /// 1= Success, 0= Failed, 2= Username Exists, 3= Email Exists
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public APIReturnModel CreateSystemUsers(SystemUserModel model)
 {
     try
     {
         if (IsUserNameExists(model.Username))
         {
             return(new APIReturnModel {
                 Status = 2
             });
         }
         if (IsEmailExists(model.Email))
         {
             return(new APIReturnModel {
                 Status = 3
             });
         }
         SystemUser user = new SystemUser
         {
             Id           = Guid.NewGuid().ToString(),
             Address      = model.Address,
             CreatedAt    = DateTime.Now,
             Email        = model.Email,
             FirstName    = model.FirstName,
             LastName     = model.LastName,
             Phone        = model.Phone,
             Username     = model.Username,
             PasswordHash = model.PasswordHash,
             IsArchived   = false
         };
         Db.SystemUsers.Add(user);
         Db.SaveChanges();
         return(new APIReturnModel {
             Status = 1, Value = user.Id.ToString()
         });
     }
     catch (Exception)
     {
         return(new APIReturnModel {
             Status = 0
         });
     }
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                base.OnActionExecuting(filterContext);
                user = (SystemUserModel)HttpContext.Current.Session["SystemUser"];

                if (!processor.isValidUser(user))
                {
                    if (!(filterContext.Controller is AccessController))
                    {
                        filterContext.HttpContext.Response.Redirect(LOGIN_VIEW);
                    }
                }
            }
            catch (Exception)
            {
                filterContext.Result = new RedirectResult(LOGIN_VIEW);
            }
        }
        public ActionResult Login(LoginValuesModel loginValues)
        {
            ActionResult loginViewResult = View();

            try
            {
                SystemUserModel user = processor.getUserFromDB(loginValues);
                if (processor.isValidUser(user))
                {
                    Session["SystemUser"] = user;
                    loginViewResult       = RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewBag.ErrorMessage = "Invalid email or password";
                }
            }
            catch (Exception error)
            {
                ViewBag.ErrorMessage = error.Message;
            }
            return(loginViewResult);
        }
Пример #28
0
        private void SaveImages(Model.Person person, SystemUserModel model)
        {
            if (model.PhotoLocationUpload != null && model.PhotoLocationUpload.ContentLength > 0)
            {
                var destinationImagePath = SettingsHelper <CommonSettings> .Settings.PersonPhotoUploadPath;
                var physicalPath         = Path.GetFullPath(Server.MapPath(destinationImagePath));
                if (!Directory.Exists(physicalPath))
                {
                    Directory.CreateDirectory(physicalPath);
                }
                var fileExtension = Path.GetExtension(model.PhotoLocationUpload.FileName);
                var newPath       = Path.Combine(destinationImagePath, Guid.NewGuid() + fileExtension);
                model.PhotoLocationUpload.SaveAs(Path.GetFullPath(Server.MapPath(newPath)));
                person.PhotoLocation = newPath.Replace('\\', '/');
            }

            if (model.SignatureImageUpload != null && model.SignatureImageUpload.ContentLength > 0)
            {
                var destination = new Byte[model.SignatureImageUpload.ContentLength];
                model.SignatureImageUpload.InputStream.Seek(0, SeekOrigin.Begin);
                model.SignatureImageUpload.InputStream.Read(destination, 0, model.SignatureImageUpload.ContentLength);
                person.SignatureImage = destination;
            }
        }
Пример #29
0
 public void AddUser(SystemUserModel user)
 {
     var query = $"insert into System_Account(ID,UserName,IsDomainAccount,Description,IsUse,RealName,Picture) values('{user.ID}','{user.UserName}',1,'{user.Description}','{user.IsUse}','{user.RealName}','{user.Picture}')";
     _repository.Excute(query);
     _repository.Connection.Close();
 }
Пример #30
0
 public bool isValidUser(SystemUserModel systemUser)
 {
     return(systemUser != null);
 }
Пример #31
0
        public SystemUserModel getUserFromDB(LoginValuesModel loginValues)
        {
            SystemUserModel externalUser = buildSystemUserModel(loginValues);

            return(systemUsersManager.getSystemUser(externalUser));
        }
Пример #32
0
 public void UpdateUser(SystemUserModel user)
 {
     var query = $"update System_Account set UserName='******',RealName='{user.RealName}',Description='{user.Description}' ,IsUse='{user.IsUse}',Picture='{user.Picture}'where ID='{user.ID}'";
     _repository.Excute(query);
     _repository.Connection.Close();
 }