Esempio n. 1
0
        public IActionResult ClearSelectedAuditLogs(IFormCollection form)
        {
            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            var auditLogIds = new List <int>();

            foreach (var key in form.Keys)
            {
                if (key.ToString().StartsWith("selectAuditLog_"))
                {
                    var eventId = int.Parse(key.ToString().Replace("selectAuditLog_", ""));
                    auditLogIds.Add(eventId);
                }
            }

            if (auditLogIds.Any())
            {
                _auditService.DeleteSelectedAuditLogs(DepartmentId, auditLogIds);
            }

            return(RedirectToAction("Audits"));
        }
Esempio n. 2
0
        public IActionResult EditDocument(int documentId)
        {
            EditDocumentView model = new EditDocumentView();

            var document = _documentsService.GetDocumentById(documentId);

            if (document.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (document.AdminsOnly && !ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            model.Name        = document.Name;
            model.Description = document.Description;
            model.Category    = document.Category;
            model.AdminOnly   = document.AdminsOnly.ToString();
            model.Document    = document;
            model.UserId      = UserId;

            return(View(model));
        }
Esempio n. 3
0
        public async Task <IActionResult> NewNote(NewNoteView model, CancellationToken cancellationToken)
        {
            if (ModelState.IsValid)
            {
                Note note = new Note();
                note.DepartmentId = DepartmentId;
                note.UserId       = UserId;
                note.AddedOn      = DateTime.UtcNow;
                note.Title        = model.Title;
                note.Body         = System.Net.WebUtility.HtmlDecode(model.Body);

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
                {
                    note.IsAdminOnly = bool.Parse(model.IsAdminOnly);
                }
                else
                {
                    note.IsAdminOnly = false;
                }

                note.Category = model.Category;

                await _notesService.SaveAsync(note, cancellationToken);

                return(RedirectToAction("Index", "Notes", new { Area = "User" }));
            }

            return(View(model));
        }
    private static bool IsAuthorized(this HtmlHelper htmlHelper, RouteValueDictionary routeValues)
    {
        var routeData = BuildRouteData(htmlHelper.RouteCollection, routeValues);
        var context   = BuildRequestContext(htmlHelper, routeData);

        return(ClaimsAuthorizationHelper.CheckAccess(context));
    }
Esempio n. 5
0
        public IActionResult Edit(EditNoteView model)
        {
            if (ModelState.IsValid)
            {
                var savedNote = _notesService.GetNoteById(model.NoteId);

                if (savedNote.DepartmentId != DepartmentId)
                {
                    Unauthorized();
                }

                savedNote.DepartmentId = DepartmentId;
                savedNote.UserId       = UserId;
                savedNote.AddedOn      = DateTime.UtcNow;
                savedNote.Title        = model.Title;
                savedNote.Body         = System.Net.WebUtility.HtmlDecode(model.Body);

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
                {
                    savedNote.IsAdminOnly = bool.Parse(model.IsAdminOnly);
                }
                else
                {
                    savedNote.IsAdminOnly = false;
                }

                savedNote.Category = model.Category;

                _notesService.Save(savedNote);

                return(RedirectToAction("Index", "Notes", new { Area = "User" }));
            }

            return(View(model));
        }
Esempio n. 6
0
        public IActionResult Audits()
        {
            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            return(View());
        }
Esempio n. 7
0
        public IActionResult DeleteAudit(int auditLogId)
        {
            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            _auditService.DeleteAuditLogById(auditLogId);

            return(RedirectToAction("Audits"));
        }
Esempio n. 8
0
        public async Task <IActionResult> GetLogsList(string year)
        {
            List <LogForListJson> logsJson = new List <LogForListJson>();

            //var logs = await _workLogsService.GetAllLogsForDepartmentAsync(DepartmentId);
            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            List <Log> logs;

            if (String.IsNullOrWhiteSpace(year))
            {
                logs = await _workLogsService.GetAllLogsForDepartmentAsync(DepartmentId);
            }
            else
            {
                logs = await _workLogsService.GetAllLogsForDepartmentAndYearAsync(DepartmentId, year);
            }

            foreach (var log in logs)
            {
                var logJson = new LogForListJson();
                logJson.LogId = log.LogId;
                logJson.Type  = ((LogTypes)log.LogType).ToString();

                if (log.StationGroup != null)
                {
                    logJson.Group = log.StationGroup.Name;
                }
                else
                {
                    logJson.Group = department.Name;
                }

                logJson.LoggedBy = await UserHelper.GetFullNameForUser(log.LoggedByUserId);

                logJson.LoggedOn = log.LoggedOn.TimeConverterToString(department);

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || log.LoggedByUserId == UserId || (log.StationGroupId.HasValue && ClaimsAuthorizationHelper.IsUserGroupAdmin(log.StationGroupId.Value)))
                {
                    logJson.CanDelete = true;
                }
                else
                {
                    logJson.CanDelete = false;
                }

                logsJson.Add(logJson);
            }

            return(Json(logsJson));
        }
Esempio n. 9
0
        public IActionResult DeleteDocument(int documentId)
        {
            var document = _documentsService.GetDocumentById(documentId);

            if (document.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || document.UserId != UserId)
            {
                Unauthorized();
            }

            _documentsService.DeleteDocument(document);

            return(RedirectToAction("Index", "Documents", new { Area = "User" }));
        }
Esempio n. 10
0
        public async Task <IActionResult> DeleteDocument(int documentId, CancellationToken cancellationToken)
        {
            var document = await _documentsService.GetDocumentByIdAsync(documentId);

            if (document.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || document.UserId != UserId)
            {
                Unauthorized();
            }

            await _documentsService.DeleteDocumentAsync(document, cancellationToken);

            return(RedirectToAction("Index", "Documents", new { Area = "User" }));
        }
Esempio n. 11
0
        public async Task <IActionResult> GetActiveCallsList(int linkId)
        {
            var link = await _departmentLinksService.GetLinkByIdAsync(linkId);

            List <CallListJson> callsJson = new List <CallListJson>();

            if (link.DepartmentId != DepartmentId && link.LinkedDepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (link.LinkEnabled && link.DepartmentShareCalls)
            {
                var calls      = (await _callsService.GetActiveCallsByDepartmentAsync(link.DepartmentId)).OrderByDescending(x => x.LoggedOn);
                var department = await _departmentsService.GetDepartmentByIdAsync(link.DepartmentId, false);

                foreach (var call in calls)
                {
                    var callJson = new CallListJson();
                    callJson.CallId     = call.CallId;
                    callJson.Number     = call.Number;
                    callJson.Name       = call.Name;
                    callJson.State      = _callsService.CallStateToString((CallStates)call.State);
                    callJson.StateColor = _callsService.CallStateToColor((CallStates)call.State);
                    callJson.Timestamp  = call.LoggedOn.TimeConverterToString(department);
                    callJson.Priority   = await _callsService.CallPriorityToStringAsync(call.Priority, link.DepartmentId);

                    callJson.Color = await _callsService.CallPriorityToColorAsync(call.Priority, link.DepartmentId);

                    if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || call.ReportingUserId == UserId)
                    {
                        callJson.CanDeleteCall = true;
                    }
                    else
                    {
                        callJson.CanDeleteCall = false;
                    }

                    callsJson.Add(callJson);
                }
            }

            return(Json(callsJson));
        }
Esempio n. 12
0
        public FileResult GetDocument(int documentId)
        {
            var document = _documentsService.GetDocumentById(documentId);

            if (document.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (document.AdminsOnly && !ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            return(new FileContentResult(document.Data, document.Type)
            {
                FileDownloadName = document.Filename
            });
        }
Esempio n. 13
0
        public IActionResult SetPermissionData(int type, string data, bool?lockToGroup)
        {
            if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                var before = _permissionsService.GetPermisionByDepartmentType(DepartmentId, (PermissionTypes)type);
                var result = _permissionsService.SetPermissionForDepartment(DepartmentId, UserId, (PermissionTypes)type, (PermissionActions)before.Action, data, lockToGroup.GetValueOrDefault());

                var auditEvent = new AuditEvent();
                auditEvent.DepartmentId = DepartmentId;
                auditEvent.UserId       = UserId;
                auditEvent.Type         = AuditLogTypes.PermissionsChanged;
                auditEvent.Before       = before.CloneJson();
                auditEvent.After        = result.CloneJson();
                _eventAggregator.SendMessage <AuditEvent>(auditEvent);

                return(new StatusCodeResult((int)HttpStatusCode.OK));
            }

            return(new StatusCodeResult((int)HttpStatusCode.NotModified));
        }
Esempio n. 14
0
        public IActionResult GetLogsList()
        {
            List <LogForListJson> logsJson = new List <LogForListJson>();

            var logs       = _workLogsService.GetAllLogsForDepartmnt(DepartmentId);
            var department = _departmentsService.GetDepartmentById(DepartmentId, false);

            foreach (var log in logs)
            {
                var logJson = new LogForListJson();
                logJson.LogId = log.LogId;
                logJson.Type  = ((LogTypes)log.LogType).ToString();

                if (log.StationGroup != null)
                {
                    logJson.Group = log.StationGroup.Name;
                }
                else
                {
                    logJson.Group = department.Name;
                }

                logJson.LoggedBy = UserHelper.GetFullNameForUser(log.LoggedBy.UserId);
                logJson.LoggedOn = log.LoggedOn.TimeConverterToString(department);

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin() || log.LoggedByUserId == UserId || (log.StationGroupId.HasValue && ClaimsAuthorizationHelper.IsUserGroupAdmin(log.StationGroupId.Value)))
                {
                    logJson.CanDelete = true;
                }
                else
                {
                    logJson.CanDelete = false;
                }

                logsJson.Add(logJson);
            }

            return(Json(logsJson));
        }
Esempio n. 15
0
        public async Task <IActionResult> ViewAudit(int auditLogId)
        {
            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            var model = new ViewAuditLogView();

            model.AuditLog = await _auditService.GetAuditLogByIdAsync(auditLogId);

            model.Department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);

            model.Type = (AuditLogTypes)model.AuditLog.LogType;

            if (model.AuditLog.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }


            return(View(model));
        }
Esempio n. 16
0
        public async Task <IActionResult> GetMapData(MapSettingsInput input)
        {
            MapDataJson dataJson = new MapDataJson();

            var calls = await _callsService.GetActiveCallsByDepartmentAsync(DepartmentId);

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(DepartmentId);

            var lastUserActionlogs = await _actionLogsService.GetLastActionLogsForDepartmentAsync(DepartmentId);

            var personnelNames = await _departmentsService.GetAllPersonnelNamesForDepartmentAsync(DepartmentId);

            var unitStates = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(DepartmentId);

            var userLocationPermission = await _permissionsService.GetPermissionByDepartmentTypeAsync(DepartmentId, PermissionTypes.CanSeePersonnelLocations);

            if (userLocationPermission != null)
            {
                var userGroup = await _departmentGroupsService.GetGroupForUserAsync(UserId, DepartmentId);

                int?groupId = null;

                if (userGroup != null)
                {
                    groupId = userGroup.DepartmentGroupId;
                }

                var roles = await _personnelRolesService.GetRolesForUserAsync(UserId, DepartmentId);

                var allowedUsers = _permissionsService.GetAllowedUsers(userLocationPermission, DepartmentId, groupId, ClaimsAuthorizationHelper.IsUserDepartmentAdmin(), ClaimsAuthorizationHelper.IsUserDepartmentAdmin(), roles);

                lastUserActionlogs.RemoveAll(x => !allowedUsers.Contains(x.UserId));
            }

            if (input.ShowDistricts)
            {
                foreach (var station in stations)
                {
                    if (!String.IsNullOrWhiteSpace(station.Geofence))
                    {
                        GeofenceJson geofence = new GeofenceJson();
                        geofence.Name  = station.Name;
                        geofence.Color = station.GeofenceColor;
                        geofence.Fence = station.Geofence;

                        dataJson.Geofences.Add(geofence);
                    }
                }
            }

            if (input.ShowStations)
            {
                foreach (var station in stations)
                {
                    try
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath         = "Station";
                        info.Title             = station.Name;
                        info.InfoWindowContent = station.Name;

                        if (station.Address != null)
                        {
                            string coordinates =
                                await _geoLocationProvider.GetLatLonFromAddress(string.Format("{0} {1} {2} {3}", station.Address.Address1,
                                                                                              station.Address.City,
                                                                                              station.Address.State,
                                                                                              station.Address.PostalCode));

                            if (!String.IsNullOrEmpty(coordinates))
                            {
                                info.Latitude  = double.Parse(coordinates.Split(char.Parse(","))[0]);
                                info.Longitude = double.Parse(coordinates.Split(char.Parse(","))[1]);

                                dataJson.Markers.Add(info);
                            }
                        }
                        else if (!String.IsNullOrWhiteSpace(station.Latitude) && !String.IsNullOrWhiteSpace(station.Longitude))
                        {
                            info.Latitude  = double.Parse(station.Latitude);
                            info.Longitude = double.Parse(station.Longitude);

                            dataJson.Markers.Add(info);
                        }
                    }
                    catch (Exception ex)
                    {
                        //Logging.LogException(ex);
                    }
                }
            }

            if (input.ShowCalls)
            {
                foreach (var call in calls)
                {
                    MapMakerInfo info = new MapMakerInfo();
                    info.ImagePath         = "Call";
                    info.Title             = call.Name;
                    info.InfoWindowContent = call.NatureOfCall;

                    if (!String.IsNullOrEmpty(call.GeoLocationData))
                    {
                        try
                        {
                            info.Latitude  = double.Parse(call.GeoLocationData.Split(char.Parse(","))[0]);
                            info.Longitude = double.Parse(call.GeoLocationData.Split(char.Parse(","))[1]);

                            dataJson.Markers.Add(info);
                        }
                        catch
                        {
                        }
                    }
                    else if (!String.IsNullOrEmpty(call.Address))
                    {
                        string coordinates = await _geoLocationProvider.GetLatLonFromAddress(call.Address);

                        if (!String.IsNullOrEmpty(coordinates))
                        {
                            info.Latitude  = double.Parse(coordinates.Split(char.Parse(","))[0]);
                            info.Longitude = double.Parse(coordinates.Split(char.Parse(","))[1]);
                        }

                        dataJson.Markers.Add(info);
                    }
                }
            }

            if (input.ShowUnits)
            {
                foreach (var unit in unitStates)
                {
                    if (unit.Latitude.HasValue && unit.Latitude.Value != 0 && unit.Longitude.HasValue &&
                        unit.Longitude.Value != 0)
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath         = "Engine_Responding";
                        info.Title             = unit.Unit.Name;
                        info.InfoWindowContent = "";
                        info.Latitude          = double.Parse(unit.Latitude.Value.ToString());
                        info.Longitude         = double.Parse(unit.Longitude.Value.ToString());

                        dataJson.Markers.Add(info);
                    }
                }
            }

            if (input.ShowPersonnel)
            {
                foreach (var person in lastUserActionlogs)
                {
                    if (!String.IsNullOrWhiteSpace(person.GeoLocationData))
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath = "Person";

                        var name = personnelNames.FirstOrDefault(x => x.UserId == person.UserId);
                        if (name != null)
                        {
                            info.Title             = name.Name;
                            info.InfoWindowContent = "";
                        }
                        else
                        {
                            info.Title             = "";
                            info.InfoWindowContent = "";
                        }

                        var infos = person.GeoLocationData.Split(char.Parse(","));
                        if (infos != null && infos.Length == 2)
                        {
                            info.Latitude  = double.Parse(infos[0]);
                            info.Longitude = double.Parse(infos[1]);

                            dataJson.Markers.Add(info);
                        }
                    }
                }
            }

            if (input.ShowPOIs)
            {
                var poiTypes = await _mappingService.GetPOITypesForDepartmentAsync(DepartmentId);

                foreach (var poiType in poiTypes)
                {
                    foreach (var poi in poiType.Pois)
                    {
                        MapMakerInfo info = new MapMakerInfo();
                        info.ImagePath         = poiType.Image;
                        info.Marker            = poiType.Marker;
                        info.Title             = poiType.Name;
                        info.InfoWindowContent = "";
                        info.Latitude          = poi.Latitude;
                        info.Longitude         = poi.Longitude;
                        info.Color             = poiType.Color;

                        dataJson.Pois.Add(info);
                    }
                }
            }

            return(Json(dataJson));
        }
Esempio n. 17
0
        public async Task <IActionResult> EditUserProfile(EditProfileModel model, IFormCollection form, CancellationToken cancellationToken)
        {
            if (!await _authorizationService.CanUserEditProfileAsync(UserId, DepartmentId, model.UserId))
            {
                Unauthorized();
            }

            model.User = _usersService.GetUserById(model.UserId);
            //model.PushUris = await _pushUriService.GetPushUrisByUserId(model.UserId);
            model.Department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);

            model.CanEnableVoice = await _limitsService.CanDepartmentUseVoiceAsync(DepartmentId);

            var groups       = new List <DepartmentGroup>();
            var defaultGroup = new DepartmentGroup();

            defaultGroup.Name = "No Group";
            groups.Add(defaultGroup);
            groups.AddRange(await _departmentGroupsService.GetAllGroupsForDepartmentAsync(model.Department.DepartmentId));
            model.Groups = new SelectList(groups, "DepartmentGroupId", "Name");

            ViewBag.Carriers  = model.Carrier.ToSelectList();
            ViewBag.Countries = new SelectList(Countries.CountryNames);
            ViewBag.TimeZones = new SelectList(TimeZones.Zones, "Key", "Value");

            if (!String.IsNullOrEmpty(model.Profile.MobileNumber))
            {
                if (model.Carrier == MobileCarriers.None)
                {
                    ModelState.AddModelError("Carrier", "If you entered a mobile phone, you need to select your mobile carrier. If you carrier is not listed select one and contact us to have your carrier added.");
                }
                else
                {
                    if (model.Carrier == MobileCarriers.VirginMobileUk && !model.Profile.MobileNumber.StartsWith("0"))
                    {
                        ModelState.AddModelError("Profile.MobileNumber", "Virgin Mobile Uk requires your phone number to start with 0.");
                    }

                    if (model.Carrier == MobileCarriers.O2 && !model.Profile.MobileNumber.StartsWith("44"))
                    {
                        ModelState.AddModelError("Profile.MobileNumber", "O2 requires your phone number to start with 44.");
                    }

                    if (model.Carrier == MobileCarriers.Orange && !model.Profile.MobileNumber.StartsWith("0"))
                    {
                        ModelState.AddModelError("Profile.MobileNumber", "Orange requires your phone number to start with 0.");
                    }

                    if (model.Carrier == MobileCarriers.TMobileUk && !model.Profile.MobileNumber.StartsWith("0"))
                    {
                        ModelState.AddModelError("Profile.MobileNumber", "T-Mobile Uk requires your phone number to start with 0.");
                    }

                    if (model.Carrier == MobileCarriers.Vodafone && !model.Profile.MobileNumber.StartsWith("0"))
                    {
                        ModelState.AddModelError("Profile.MobileNumber", "Vodafone requires your phone number to start with 0.");
                    }
                }
            }

            if ((model.Profile.SendSms || model.Profile.SendMessageSms || model.Profile.SendMessageSms) && String.IsNullOrEmpty(model.Profile.MobileNumber))
            {
                ModelState.AddModelError("Profile.MobileNumber", "You have selected you want SMS/Text notifications but have not supplied a mobile number.");
            }

            // They specified a street address for physical
            if (!String.IsNullOrWhiteSpace(model.PhysicalAddress1))
            {
                if (String.IsNullOrEmpty(model.PhysicalCity))
                {
                    ModelState.AddModelError("City", string.Format("The Physical City field is required"));
                }

                if (String.IsNullOrEmpty(model.PhysicalCountry))
                {
                    ModelState.AddModelError("Country", string.Format("The Physical Country field is required"));
                }

                if (String.IsNullOrEmpty(model.PhysicalPostalCode))
                {
                    ModelState.AddModelError("PostalCode", string.Format("The Physical Postal Code field is required"));
                }

                if (String.IsNullOrEmpty(model.PhysicalState))
                {
                    ModelState.AddModelError("State", string.Format("The Physical State/Provence field is required"));
                }
            }

            if (!String.IsNullOrWhiteSpace(model.MailingAddress1) && !model.MailingAddressSameAsPhysical)
            {
                if (String.IsNullOrEmpty(model.MailingCity))
                {
                    ModelState.AddModelError("City", string.Format("The Mailing City field is required"));
                }

                if (String.IsNullOrEmpty(model.MailingCountry))
                {
                    ModelState.AddModelError("Country", string.Format("The Mailing Country field is required"));
                }

                if (String.IsNullOrEmpty(model.MailingPostalCode))
                {
                    ModelState.AddModelError("PostalCode", string.Format("The Mailing Postal Code field is required"));
                }

                if (String.IsNullOrEmpty(model.MailingState))
                {
                    ModelState.AddModelError("State", string.Format("The Mailing State/Provence field is required"));
                }
            }

            if (model.User.Email != model.Email)
            {
                var currentEmail = _usersService.GetUserByEmail(model.Email);

                if (currentEmail != null && currentEmail.Id != model.User.UserId.ToString())
                {
                    ModelState.AddModelError("Email", "Email Address Already in Use. Please use another one.");
                }
            }

            if (model.Profile.VoiceForCall)
            {
                if (model.Profile.VoiceCallHome && String.IsNullOrWhiteSpace(model.Profile.HomeNumber))
                {
                    ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting for your home phone number but have not supplied a home phone number. Please supply one.");
                }

                if (model.Profile.VoiceCallMobile && String.IsNullOrWhiteSpace(model.Profile.MobileNumber))
                {
                    ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting for your mobile phone number but have not supplied a mobile phone number. Please supply one.");
                }

                if (!model.Profile.VoiceCallHome && !model.Profile.VoiceCallMobile)
                {
                    ModelState.AddModelError("VoiceForCall", "You selected to Enable Telephone alerting, but you didn't select a number to call you at. Please select either/both home phone or mobile phone.");
                }
            }

            if (model.IsOwnProfile)
            {
                bool checkPasswordSuccess = false;
                if (string.IsNullOrEmpty(model.OldPassword) == false && string.IsNullOrEmpty(model.NewPassword) == false)
                {
                    try
                    {
                        checkPasswordSuccess = await _userManager.CheckPasswordAsync(model.User, model.OldPassword);
                    }
                    catch (Exception)
                    {
                        checkPasswordSuccess = false;
                    }

                    if (!checkPasswordSuccess)
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }

                if (!String.IsNullOrWhiteSpace(model.NewUsername))
                {
                    var newUser = await _userManager.FindByNameAsync(model.NewUsername);

                    if (newUser != null)
                    {
                        ModelState.AddModelError("", "The NEW username you have supplied is already in use, please try another one. If you didn't mean to update your username please leave that field blank.");
                    }
                }
            }

            if (ModelState.IsValid)
            {
                Address homeAddress    = null;
                Address mailingAddress = null;

                var auditEvent = new AuditEvent();
                auditEvent.DepartmentId = DepartmentId;
                auditEvent.UserId       = UserId;
                auditEvent.Type         = AuditLogTypes.ProfileUpdated;

                var savedProfile = await _userProfileService.GetProfileByUserIdAsync(model.UserId);

                if (savedProfile == null)
                {
                    savedProfile = new UserProfile();
                }

                auditEvent.Before = savedProfile.CloneJson();

                savedProfile.UserId                  = model.UserId;
                savedProfile.MobileCarrier           = (int)model.Carrier;
                savedProfile.FirstName               = model.FirstName;
                savedProfile.LastName                = model.LastName;
                savedProfile.MobileNumber            = model.Profile.MobileNumber;
                savedProfile.SendEmail               = model.Profile.SendEmail;
                savedProfile.SendPush                = model.Profile.SendPush;
                savedProfile.SendSms                 = model.Profile.SendSms;
                savedProfile.SendMessageEmail        = model.Profile.SendMessageEmail;
                savedProfile.SendMessagePush         = model.Profile.SendMessagePush;
                savedProfile.SendMessageSms          = model.Profile.SendMessageSms;
                savedProfile.SendNotificationEmail   = model.Profile.SendNotificationEmail;
                savedProfile.SendNotificationPush    = model.Profile.SendNotificationPush;
                savedProfile.SendNotificationSms     = model.Profile.SendNotificationSms;
                savedProfile.DoNotRecieveNewsletters = model.Profile.DoNotRecieveNewsletters;
                savedProfile.HomeNumber              = model.Profile.HomeNumber;
                savedProfile.IdentificationNumber    = model.Profile.IdentificationNumber;
                savedProfile.TimeZone                = model.Profile.TimeZone;

                if (model.CanEnableVoice)
                {
                    savedProfile.VoiceForCall = model.Profile.VoiceForCall;

                    if (savedProfile.VoiceForCall)
                    {
                        savedProfile.VoiceCallHome   = model.Profile.VoiceCallHome;
                        savedProfile.VoiceCallMobile = model.Profile.VoiceCallMobile;
                    }
                    else
                    {
                        savedProfile.VoiceCallHome   = false;
                        savedProfile.VoiceCallMobile = false;
                    }
                }
                else
                {
                    savedProfile.VoiceForCall    = false;
                    savedProfile.VoiceCallHome   = false;
                    savedProfile.VoiceCallMobile = false;
                }

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
                {
                    var currentGroup = await _departmentGroupsService.GetGroupForUserAsync(model.UserId, DepartmentId);

                    if (model.UserGroup != 0 && (currentGroup == null || currentGroup.DepartmentGroupId != model.UserGroup))
                    {
                        await _departmentGroupsService.MoveUserIntoGroupAsync(model.UserId, model.UserGroup, model.IsUserGroupAdmin, DepartmentId, cancellationToken);
                    }
                    else if (currentGroup != null && currentGroup.DepartmentGroupId == model.UserGroup)
                    {
                        var member = await _departmentGroupsService.GetGroupMemberForUserAsync(model.UserId, DepartmentId);

                        if (member != null)
                        {
                            member.IsAdmin = model.IsUserGroupAdmin;
                            _departmentGroupsService.SaveGroupMember(member);
                        }
                    }
                    else if (model.UserGroup <= 0)
                    {
                        await _departmentGroupsService.DeleteUserFromGroupsAsync(model.UserId, DepartmentId, cancellationToken);
                    }
                }

                if (form.ContainsKey("roles"))
                {
                    var roles = form["roles"].ToString().Split(char.Parse(","));

                    if (roles.Any())
                    {
                        await _personnelRolesService.SetRolesForUserAsync(DepartmentId, model.UserId, roles, cancellationToken);
                    }
                }

                if (savedProfile.HomeAddressId.HasValue)
                {
                    homeAddress = await _addressService.GetAddressByIdAsync(savedProfile.HomeAddressId.Value);
                }

                if (savedProfile.MailingAddressId.HasValue)
                {
                    mailingAddress = await _addressService.GetAddressByIdAsync(savedProfile.MailingAddressId.Value);
                }

                if (!model.MailingAddressSameAsPhysical && homeAddress != null && mailingAddress != null &&
                    (homeAddress.AddressId == mailingAddress.AddressId))
                {
                    mailingAddress = new Address();
                }

                if (!String.IsNullOrWhiteSpace(model.PhysicalAddress1))
                {
                    if (homeAddress == null)
                    {
                        homeAddress = new Address();
                    }

                    homeAddress.Address1   = model.PhysicalAddress1;
                    homeAddress.City       = model.PhysicalCity;
                    homeAddress.Country    = model.PhysicalCountry;
                    homeAddress.PostalCode = model.PhysicalPostalCode;
                    homeAddress.State      = model.PhysicalState;

                    homeAddress = await _addressService.SaveAddressAsync(homeAddress, cancellationToken);

                    savedProfile.HomeAddressId = homeAddress.AddressId;

                    if (model.MailingAddressSameAsPhysical)
                    {
                        savedProfile.MailingAddressId = homeAddress.AddressId;
                    }
                }

                if (!String.IsNullOrWhiteSpace(model.MailingAddress1) && !model.MailingAddressSameAsPhysical)
                {
                    if (mailingAddress == null)
                    {
                        mailingAddress = new Address();
                    }

                    mailingAddress.Address1   = model.MailingAddress1;
                    mailingAddress.City       = model.MailingCity;
                    mailingAddress.Country    = model.MailingCountry;
                    mailingAddress.PostalCode = model.MailingPostalCode;
                    mailingAddress.State      = model.MailingState;

                    mailingAddress = await _addressService.SaveAddressAsync(mailingAddress, cancellationToken);

                    savedProfile.MailingAddressId = mailingAddress.AddressId;
                }

                savedProfile.LastUpdated = DateTime.UtcNow;
                await _userProfileService.SaveProfileAsync(DepartmentId, savedProfile, cancellationToken);

                auditEvent.After = savedProfile.CloneJson();
                _eventAggregator.SendMessage <AuditEvent>(auditEvent);

                var depMember = await _departmentsService.GetDepartmentMemberAsync(model.UserId, DepartmentId);

                if (depMember != null)
                {
                    // Users Department Admin status changes, invalid the department object in cache.
                    if (model.IsDepartmentAdmin != depMember.IsAdmin)
                    {
                        _departmentsService.InvalidateDepartmentInCache(depMember.DepartmentId);
                    }

                    depMember.IsAdmin    = model.IsDepartmentAdmin;
                    depMember.IsDisabled = model.IsDisabled;
                    depMember.IsHidden   = model.IsHidden;

                    await _departmentsService.SaveDepartmentMemberAsync(depMember, cancellationToken);
                }

                if (!model.Profile.DoNotRecieveNewsletters)
                {
                    Unsubscribe(model.Email);
                }

                //var membershipUser = Membership.GetUser(model.UserId);
                //membershipUser.Email = model.Email;
                //Membership.UpdateUser(membershipUser);

                _usersService.UpdateEmail(model.User.Id, model.Email);

                if (model.IsOwnProfile)
                {
                    // Change Password
                    if (!string.IsNullOrEmpty(model.OldPassword) && !string.IsNullOrEmpty(model.NewPassword))
                    {
                        var identityUser = await _userManager.FindByIdAsync(model.User.Id);

                        var result = await _userManager.ChangePasswordAsync(identityUser, model.OldPassword, model.NewPassword);
                    }

                    if (!string.IsNullOrWhiteSpace(model.NewUsername))
                    {
                        _usersService.UpdateUsername(model.User.UserName, model.NewUsername);
                    }
                }

                _userProfileService.ClearUserProfileFromCache(model.UserId);
                _userProfileService.ClearAllUserProfilesFromCache(model.Department.DepartmentId);
                _departmentsService.InvalidateDepartmentUsersInCache(model.Department.DepartmentId);
                _departmentsService.InvalidatePersonnelNamesInCache(DepartmentId);
                _departmentsService.InvalidateDepartmentMembers();
                _usersService.ClearCacheForDepartment(DepartmentId);

                return(RedirectToAction("Index", "Personnel", new { area = "User" }));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 18
0
        public IActionResult NewDocument(NewDocumentView model, IFormFile fileToUpload)
        {
            //file = Request.Files["fileToUpload"];

            if (fileToUpload == null || fileToUpload.Length <= 0)
            {
                ModelState.AddModelError("fileToUpload", "You must select a document to add.");
            }
            else
            {
                var extenion = fileToUpload.FileName.Substring(fileToUpload.FileName.IndexOf(char.Parse(".")) + 1,
                                                               fileToUpload.FileName.Length - fileToUpload.FileName.IndexOf(char.Parse(".")) - 1);

                if (!String.IsNullOrWhiteSpace(extenion))
                {
                    extenion = extenion.ToLower();
                }

                if (extenion != "jpg" && extenion != "jpeg" && extenion != "png" && extenion != "gif" && extenion != "gif" && extenion != "pdf" && extenion != "doc" &&
                    extenion != "docx" && extenion != "ppt" && extenion != "pptx" && extenion != "pps" && extenion != "ppsx" && extenion != "odt" &&
                    extenion != "xls" && extenion != "xlsx" && extenion != "mp3" && extenion != "m4a" && extenion != "ogg" && extenion != "wav" &&
                    extenion != "mp4" && extenion != "m4v" && extenion != "mov" && extenion != "wmv" && extenion != "avi" && extenion != "mpg" && extenion != "txt")
                {
                    ModelState.AddModelError("fileToUpload", string.Format("Document type ({0}) is not importable.", extenion));
                }

                if (fileToUpload.Length > 10000000)
                {
                    ModelState.AddModelError("fileToUpload", "Document is too large, must be smaller then 10MB.");
                }
            }

            if (ModelState.IsValid)
            {
                Document doc = new Document();
                doc.DepartmentId = DepartmentId;
                doc.UserId       = UserId;
                doc.AddedOn      = DateTime.UtcNow;
                doc.Name         = model.Name;
                doc.Description  = model.Description;

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
                {
                    doc.AdminsOnly = bool.Parse(model.AdminOnly);
                }
                else
                {
                    doc.AdminsOnly = false;
                }

                doc.Type     = fileToUpload.ContentType;
                doc.Category = model.Category;
                doc.Filename = fileToUpload.FileName;

                byte[] uploadedFile = new byte[fileToUpload.OpenReadStream().Length];
                fileToUpload.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                doc.Data = uploadedFile;

                _documentsService.SaveDocument(doc);

                _eventAggregator.SendMessage <DocumentAddedEvent>(new DocumentAddedEvent()
                {
                    DepartmentId = DepartmentId, Document = doc
                });

                return(RedirectToAction("Index", "Documents", new { Area = "User" }));
            }

            return(View(model));
        }
Esempio n. 19
0
        public IActionResult Index()
        {
            if (!ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            var model = new PermissionsView();

            var permissions = _permissionsService.GetAllPermissionsForDepartment(DepartmentId);

            int val = (int)PermissionTypes.AddPersonnel;

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.AddPersonnel))
            {
                model.AddUsers = permissions.First(x => x.PermissionType == (int)PermissionTypes.AddPersonnel).Action;
            }

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.RemovePersonnel))
            {
                model.RemoveUsers = permissions.First(x => x.PermissionType == (int)PermissionTypes.RemovePersonnel).Action;
            }

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateCall))
            {
                model.CreateCall = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateCall).Action;
            }
            else
            {
                model.CreateCall = 3;
            }

            var userAddPermissions = new List <dynamic>();

            userAddPermissions.Add(new { Id = 0, Name = "Department Admins" });
            userAddPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            model.AddUserPermissions = new SelectList(userAddPermissions, "Id", "Name");

            var userDeletePermissions = new List <dynamic>();

            userDeletePermissions.Add(new { Id = 0, Name = "Department Admins" });
            userDeletePermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            model.RemoveUserPermissions = new SelectList(userDeletePermissions, "Id", "Name");

            var createCallPermissions = new List <dynamic>();

            createCallPermissions.Add(new { Id = 3, Name = "Everyone" });
            createCallPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createCallPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createCallPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateCallPermissions = new SelectList(createCallPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateTraining))
            {
                model.CreateTraining = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateTraining).Action;
            }

            var createTrainingPermissions = new List <dynamic>();

            createTrainingPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createTrainingPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createTrainingPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateTrainingPermissions = new SelectList(createTrainingPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateDocument))
            {
                model.CreateDocument = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateDocument).Action;
            }
            else
            {
                model.CreateDocument = 3;
            }

            var createDocumentPermissions = new List <dynamic>();

            createDocumentPermissions.Add(new { Id = 3, Name = "Everyone" });
            createDocumentPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createDocumentPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createDocumentPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateDocumentPermissions = new SelectList(createDocumentPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateCalendarEntry))
            {
                model.CreateCalendarEntry = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateCalendarEntry).Action;
            }
            else
            {
                model.CreateCalendarEntry = 3;
            }

            var createCalendarEntryPermissions = new List <dynamic>();

            createCalendarEntryPermissions.Add(new { Id = 3, Name = "Everyone" });
            createCalendarEntryPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createCalendarEntryPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createCalendarEntryPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateCalendarEntryPermissions = new SelectList(createCalendarEntryPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateNote))
            {
                model.CreateNote = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateNote).Action;
            }
            else
            {
                model.CreateNote = 3;
            }

            var createNotePermissions = new List <dynamic>();

            createNotePermissions.Add(new { Id = 3, Name = "Everyone" });
            createNotePermissions.Add(new { Id = 0, Name = "Department Admins" });
            createNotePermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createNotePermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateNotePermissions = new SelectList(createNotePermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateLog))
            {
                model.CreateLog = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateLog).Action;
            }
            else
            {
                model.CreateLog = 3;
            }

            var createLogPermissions = new List <dynamic>();

            createLogPermissions.Add(new { Id = 3, Name = "Everyone" });
            createLogPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createLogPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createLogPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateLogPermissions = new SelectList(createLogPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateShift))
            {
                model.CreateShift = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateShift).Action;
            }

            var createShiftPermissions = new List <dynamic>();

            createShiftPermissions.Add(new { Id = 0, Name = "Department Admins" });
            createShiftPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createShiftPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateShiftPermissions = new SelectList(createShiftPermissions, "Id", "Name");

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.ViewPersonalInfo))
            {
                model.ViewPersonalInfo = permissions.First(x => x.PermissionType == (int)PermissionTypes.ViewPersonalInfo).Action;
            }
            else
            {
                model.ViewPersonalInfo = 3;
            }

            var viewPersonalInfoPermissions = new List <dynamic>();

            viewPersonalInfoPermissions.Add(new { Id = 3, Name = "Everyone" });
            viewPersonalInfoPermissions.Add(new { Id = 0, Name = "Department Admins" });
            viewPersonalInfoPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            viewPersonalInfoPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.ViewPersonalInfoPermissions = new SelectList(viewPersonalInfoPermissions, "Id", "Name");

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.AdjustInventory))
            {
                model.AdjustInventory = permissions.First(x => x.PermissionType == (int)PermissionTypes.AdjustInventory).Action;
            }
            else
            {
                model.AdjustInventory = 3;
            }

            var adjustInventoryPermissions = new List <dynamic>();

            adjustInventoryPermissions.Add(new { Id = 3, Name = "Everyone" });
            adjustInventoryPermissions.Add(new { Id = 0, Name = "Department Admins" });
            adjustInventoryPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            adjustInventoryPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.AdjustInventoryPermissions = new SelectList(adjustInventoryPermissions, "Id", "Name");

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CanSeePersonnelLocations))
            {
                model.ViewPersonnelLocation           = permissions.First(x => x.PermissionType == (int)PermissionTypes.CanSeePersonnelLocations).Action;
                model.LockViewPersonneLocationToGroup = permissions.First(x => x.PermissionType == (int)PermissionTypes.CanSeePersonnelLocations).LockToGroup;
            }
            else
            {
                model.ViewPersonnelLocation = 3;
            }

            var viewPersonnelLocationPermissions = new List <dynamic>();

            viewPersonnelLocationPermissions.Add(new { Id = 3, Name = "Everyone" });
            viewPersonnelLocationPermissions.Add(new { Id = 0, Name = "Department Admins" });
            viewPersonnelLocationPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            viewPersonnelLocationPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.ViewPersonnelLocationPermissions = new SelectList(viewPersonnelLocationPermissions, "Id", "Name");

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CanSeeUnitLocations))
            {
                model.ViewUnitLocation            = permissions.First(x => x.PermissionType == (int)PermissionTypes.CanSeeUnitLocations).Action;
                model.LockViewUnitLocationToGroup = permissions.First(x => x.PermissionType == (int)PermissionTypes.CanSeeUnitLocations).LockToGroup;
            }
            else
            {
                model.ViewUnitLocation = 3;
            }

            var viewUnitLocationPermissions = new List <dynamic>();

            viewUnitLocationPermissions.Add(new { Id = 3, Name = "Everyone" });
            viewUnitLocationPermissions.Add(new { Id = 0, Name = "Department Admins" });
            viewUnitLocationPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            viewUnitLocationPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.ViewUnitLocationPermissions = new SelectList(viewUnitLocationPermissions, "Id", "Name");


            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.CreateMessage))
            {
                model.CreateMessage = permissions.First(x => x.PermissionType == (int)PermissionTypes.CreateMessage).Action;
            }
            else
            {
                model.CreateMessage = 3;
            }

            var createMessagePermissions = new List <dynamic>();

            createMessagePermissions.Add(new { Id = 3, Name = "Everyone" });
            createMessagePermissions.Add(new { Id = 0, Name = "Department Admins" });
            createMessagePermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            createMessagePermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.CreateMessagePermissions = new SelectList(createMessagePermissions, "Id", "Name");

            if (permissions.Any(x => x.PermissionType == (int)PermissionTypes.ViewGroupUsers))
            {
                model.ViewGroupsUsers = permissions.First(x => x.PermissionType == (int)PermissionTypes.ViewGroupUsers).Action;
            }
            else
            {
                model.ViewGroupsUsers = 3;
            }

            var viewGroupUsersPermissions = new List <dynamic>();

            viewGroupUsersPermissions.Add(new { Id = 3, Name = "Everyone" });
            viewGroupUsersPermissions.Add(new { Id = 0, Name = "Department Admins" });
            viewGroupUsersPermissions.Add(new { Id = 1, Name = "Department and Group Admins" });
            viewGroupUsersPermissions.Add(new { Id = 2, Name = "Department Admins and Select Roles" });
            model.ViewGroupUsersPermissions = new SelectList(viewGroupUsersPermissions, "Id", "Name");

            return(View(model));
        }
Esempio n. 20
0
        public IActionResult EditDocument(EditDocumentView model, IFormFile fileToUpload)
        {
            var document = _documentsService.GetDocumentById(model.DocumentId);

            if (document.DepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            if (document.AdminsOnly && !ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
            {
                Unauthorized();
            }

            if (fileToUpload != null && fileToUpload.Length > 0)
            {
                var extenion = fileToUpload.FileName.Substring(fileToUpload.FileName.IndexOf(char.Parse(".")) + 1,
                                                               fileToUpload.FileName.Length - fileToUpload.FileName.IndexOf(char.Parse(".")) - 1);

                if (!String.IsNullOrWhiteSpace(extenion))
                {
                    extenion = extenion.ToLower();
                }

                if (extenion != "jpg" && extenion != "jpeg" && extenion != "png" && extenion != "gif" && extenion != "gif" && extenion != "pdf" && extenion != "doc" &&
                    extenion != "docx" && extenion != "ppt" && extenion != "pptx" && extenion != "pps" && extenion != "ppsx" && extenion != "odt" &&
                    extenion != "xls" && extenion != "xlsx" && extenion != "mp3" && extenion != "m4a" && extenion != "ogg" && extenion != "wav" &&
                    extenion != "mp4" && extenion != "m4v" && extenion != "mov" && extenion != "wmv" && extenion != "avi" && extenion != "mpg" && extenion != "txt")
                {
                    ModelState.AddModelError("fileToUpload", "Document type (extension) is not importable.");
                }

                if (fileToUpload.Length > 10000000)
                {
                    ModelState.AddModelError("fileToUpload", "Document is too large, must be smaller then 10MB.");
                }
            }

            if (ModelState.IsValid)
            {
                document.Name        = model.Name;
                document.Description = model.Description;

                if (ClaimsAuthorizationHelper.IsUserDepartmentAdmin())
                {
                    document.AdminsOnly = bool.Parse(model.AdminOnly);
                }
                else
                {
                    document.AdminsOnly = false;
                }

                document.Category = model.Category;

                if (fileToUpload != null && fileToUpload.Length > 0)
                {
                    document.Type     = fileToUpload.ContentType;
                    document.Filename = fileToUpload.FileName;

                    byte[] uploadedFile = new byte[fileToUpload.OpenReadStream().Length];
                    fileToUpload.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                    document.Data = uploadedFile;
                }

                _documentsService.SaveDocument(document);

                return(RedirectToAction("Index", "Documents", new { Area = "User" }));
            }

            return(View(model));
        }