public JObject UpdateGroupPerms([NakedBody] String rawData)
        {
            String  ErrorMsg;
            JObject response = new JObject();

            JObject request = JObject.Parse(rawData);

            Int32 groupKey = request["groupKey"].Value <Int32>();


            List <KeyDbManager.GroupPermEntry> newEntrys = new List <KeyDbManager.GroupPermEntry>();

            JsonConvert.PopulateObject(request["newPerms"].ToString(), newEntrys);

            if (!KeyDbManager.UpdateGroupPerms(groupKey, newEntrys, out ErrorMsg))
            {
                response["message"]  = ErrorMsg;
                response["groupKey"] = groupKey;
            }


            response["message"]  = "Update Group Success";
            response["groupKey"] = groupKey;

            return(response);
        }
Exemplo n.º 2
0
        public JObject EditUser([NakedBody] String rawData)
        {
            String ErrorMsg;

            //Try to Parse JObject
            JObject request;

            request = JObject.Parse(rawData);
            JObject response = new JObject();


            Int32   userKey    = request["userKey"].Value <Int32>();
            String  userName   = request["userName"].Value <String>();
            Int32   cardID     = request["cardID"].Value <Int32>();
            Boolean cardActive = request["cardActive"].Value <Boolean>();

            List <Int32> groupPerms = JsonConvert.DeserializeObject <List <Int32> >(request["groupPerms"].ToString());

            //Add To Database With Default Perms. (CardActive, No Groups)
            if (!KeyDbManager.EditUser(userKey, userName, cardID, groupPerms, cardActive, out ErrorMsg))
            {
                //Add Failed
                response["message"] = ErrorMsg;
                return(response);
            }


            //Success Response
            response["message"] = "User Edit Success";
            response["userKey"] = userKey;
            return(response);
        }
        public JObject ListGroupPerms()
        {
            JObject result = new JObject();

            String ErrorMsg;
            List <KeyDbManager.ControllerInfo> controllers = KeyDbManager.ListControllers(out ErrorMsg);

            if (ErrorMsg != null)
            {
                result["message"] = ErrorMsg;
                return(result);
            }

            List <KeyDbManager.GroupPermDesc> permEntries = new List <KeyDbManager.GroupPermDesc>();

            foreach (KeyDbManager.ControllerInfo ci in controllers)
            {
                permEntries.Add(new KeyDbManager.GroupPermDesc(ci.controllerSerial, 1, ci.door1Name));
                permEntries.Add(new KeyDbManager.GroupPermDesc(ci.controllerSerial, 2, ci.door2Name));
                permEntries.Add(new KeyDbManager.GroupPermDesc(ci.controllerSerial, 3, ci.door3Name));
                permEntries.Add(new KeyDbManager.GroupPermDesc(ci.controllerSerial, 4, ci.door4Name));
            }

            result["message"]      = $" Doors Found: {permEntries.Count}";
            result["doorPermDesc"] = JToken.FromObject(permEntries);

            return(result);
        }
        public JObject ListControllers()
        {
            //Try to Parse JObject
            JObject response = new JObject();


            String ErrorMsg;
            //Add To Database With Default Names
            List <KeyDbManager.ControllerInfo> controllers = KeyDbManager.ListControllers(out ErrorMsg);

            if (ErrorMsg != null)
            {
                response["message"] = ErrorMsg;
                return(response);
            }

            if (controllers == null || controllers.Count == 0)
            {
                response["message"] = "No Controllers installed";
                return(response);
            }

            //Success Response
            response["message"]     = controllers.Count + " Controllers Installed";
            response["controllers"] = JToken.FromObject(controllers);

            return(response);
        }
Exemplo n.º 5
0
        public JObject CreateApiKey([NakedBody] String rawData)
        {
            JObject response = new JObject();
            String  ErrorMsg;

            //Get ApiKey from Auth Header
            String creatorApiToken = Request.Headers.Authorization.Parameter;

            //Try to Parse JObject
            JObject request;

            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }

            //Check TokenID Format
            if (request["tokenID"] == null || request["tokenID"].Value <String>() == null || request["tokenID"].Value <String>() == "" || request["tokenID"].Value <String>().Length > 64)
            {
                response["message"] = "Invalid TokenID";
                return(response);
            }

            //Get Creator Username and Sid Based on APi Key
            KeyDbManager.TokenResponse creatorToken = KeyDbManager.LookupApiToken(creatorApiToken, out ErrorMsg);

            if (creatorToken == null)
            {
                response["message"] = ErrorMsg;
                return(response);
            }

            //Create New APi Token
            KeyDbManager.TokenResponse tokenResp = KeyDbManager.CreateAPIKey(creatorToken.userName, creatorToken.userSID, request["tokenID"].Value <String>(), out ErrorMsg);

            if (tokenResp == null)
            {
                response["message"] = ErrorMsg;
                return(response);
            }

            //Return New Entry
            response["message"]   = "Create ApiToken Success";
            response["tokenData"] = JToken.FromObject(tokenResp);
            return(response);
        }
        public JObject SaveController([NakedBody] String rawData)
        {
            //Try to Parse JObject
            JObject request;
            JObject response = new JObject();

            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }


            //Check Serial Number Format
            if (request["serial"] == null)
            {
                response["message"] = "Invalid Serial";
                return(response);
            }

            UInt16 serialNum;

            if (!UInt16.TryParse(request["serial"].Value <String>(), out serialNum))
            {
                response["message"] = "Serial Number";
                return(response);
            }


            String ErrorMsg;

            //Add To Database With Default Names
            if (!KeyDbManager.AddController("Controller#" + serialNum, serialNum, serialNum + "-1", serialNum + "-2", serialNum + "-3", serialNum + "-4", out ErrorMsg))
            {
                //Add Failed
                response["message"] = ErrorMsg;
                return(response);
            }

            //Success Response
            response["message"]      = "Controller Edit Success";
            response["controllerSN"] = serialNum;
            return(response);
        }
Exemplo n.º 7
0
        public JObject ListApiKeys()
        {
            String ErrorMsg;
            List <KeyDbManager.TokenResponse> tokenResp = KeyDbManager.ListAPIKeys(out ErrorMsg);

            JObject response = new JObject();

            if (ErrorMsg != null)
            {
                response["message"] = ErrorMsg;
                response["apikeys"] = null;
                return(response);
            }

            response["message"] = "Success";
            response["apiKeys"] = JToken.FromObject(tokenResp);
            return(response);
        }
Exemplo n.º 8
0
        public JObject DeleteApiKey([NakedBody] String rawData)
        {
            String  ErrorMsg;
            JObject response = new JObject();

            JObject request = JObject.Parse(rawData);

            KeyDbManager.TokenResponse tokenResp = KeyDbManager.DeleteAPIKey(request["apiKey"].Value <String>(), out ErrorMsg);

            if (tokenResp == null)
            {
                response["message"] = ErrorMsg;
                return(response);
            }

            response["message"]   = "Deletet ApiToken Success";
            response["tokenData"] = JToken.FromObject(tokenResp);
            return(response);
        }
Exemplo n.º 9
0
        public JObject DeleteUser([NakedBody] String rawData)
        {
            String ErrorMsg;

            //Try to Parse JObject
            JObject request;
            JObject response = new JObject();

            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }


            UInt32 userKey;

            if (!UInt32.TryParse(request["userKey"].Value <String>(), out userKey))
            {
                response["message"] = "Invalid User Key";
                return(response);
            }


            //Delete User
            if (!KeyDbManager.DeleteUser(userKey, out ErrorMsg))
            {
                //Delete Failed
                response["message"] = ErrorMsg;
                return(response);
            }


            //Success Response
            response["message"] = "Delete User Success";
            response["userKey"] = userKey;
            return(response);
        }
Exemplo n.º 10
0
        public JObject AddUser([NakedBody] String rawData)
        {
            String ErrorMsg;

            //Try to Parse JObject
            JObject request;
            JObject response = new JObject();

            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }


            UInt32 cardID;

            if (!UInt32.TryParse(request["cardID"].Value <String>(), out cardID))
            {
                response["message"] = "Invalid Card Number";
                return(response);
            }


            //Add To Database With Default Perms. (CardActive, No Groups)
            if (!KeyDbManager.AddUser(request["userName"].Value <String>(), cardID, out ErrorMsg))
            {
                //Add Failed
                response["message"] = ErrorMsg;
                return(response);
            }


            //Success Response
            response["message"] = "User Add Success";
            response["cardID"]  = cardID;
            return(response);
        }
Exemplo n.º 11
0
        public JObject ListGroups()
        {
            JObject response = new JObject();


            //Controller Serial Number
            //Number Of controllers
            String ErrorMsg;
            List <KeyDbManager.GroupSummary> groupsList = KeyDbManager.ListGroups(out ErrorMsg);

            if (ErrorMsg != null)
            {
                //Add Failed
                response["message"] = ErrorMsg;
                return(response);
            }

            response["message"] = $"{groupsList.Count} Groups Found";
            response["groups"]  = JToken.FromObject(groupsList);
            return(response);
        }
Exemplo n.º 12
0
        public JObject DeleteGroup([NakedBody] String rawData)
        {
            String  ErrorMsg;
            JObject response = new JObject();

            JObject request = JObject.Parse(rawData);

            Int32 groupKey = request["groupKey"].Value <Int32>();


            if (!KeyDbManager.DeleteGroup(groupKey, out ErrorMsg))
            {
                response["message"]  = ErrorMsg;
                response["groupKey"] = groupKey;
            }

            response["message"]  = "Delete Group Success";
            response["groupKey"] = groupKey;

            return(response);
        }
Exemplo n.º 13
0
        public JObject ListUsers()
        {
            String ErrorMsg;

            JObject response = new JObject();


            //Get List Of Users and Associated Groups
            List <KeyDbManager.UserSummary> userSummary = KeyDbManager.ListUsers(out ErrorMsg);

            if (ErrorMsg != null)
            {
                //List Users Failed
                response["message"] = ErrorMsg;
                return(response);
            }

            //Success Response
            response["message"]     = $"{userSummary.Count} Users Found";
            response["userSummary"] = JToken.FromObject(userSummary);
            return(response);
        }
Exemplo n.º 14
0
        public JObject ValidateDB()
        {
            JObject request = JObject.Parse(Request.Content.ReadAsStringAsync().Result);

            JObject response = new JObject();

            String ErrorMsg;

            //Check DB
            if (!KeyDbManager.ValidateDB(out ErrorMsg))
            {
                //Response if DB Not Initialized. Should only be if something has gone horribly wrong.
                response.Add(new JProperty("message", $"DB Validate Failed: {ErrorMsg}"));
                response.Add(new JProperty("isValid", false));
                return(response);
            }

            //Success Response
            response.Add(new JProperty("message", $"DB Validate Success"));
            response.Add(new JProperty("isValid", true));
            return(response);
        }
Exemplo n.º 15
0
        public JObject CreateGroup([NakedBody] String rawData)
        {
            String  ErrorMsg;
            JObject response = new JObject();

            JObject request = JObject.Parse(rawData);

            //Check GroupName
            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }

            //Check GroupName Format
            if (request["groupName"] == null || request["groupName"].Value <String>() == null || request["groupName"].Value <String>() == "" || request["groupName"].Value <String>().Length > 64)
            {
                response["message"] = "Invalid Group Name";
                return(response);
            }


            if (!KeyDbManager.CreateGroup(request["groupName"].Value <String>(), out ErrorMsg))
            {
                response["message"]   = ErrorMsg;
                response["groupName"] = request["groupName"].Value <String>();
            }


            response["message"]   = "Create Group Success";
            response["groupName"] = request["groupName"].Value <String>();

            return(response);
        }
Exemplo n.º 16
0
        public JObject Post()
        {
            JObject request = JObject.Parse(Request.Content.ReadAsStringAsync().Result);

            JObject response = new JObject();


            //Input Validation
            JToken jUsername;

            if (!request.TryGetValue("username", out jUsername))
            {
                response.Add(new JProperty("message", "Error: Username Not Sent"));
                return(response);
            }


            JToken jPassword;

            if (!request.TryGetValue("password", out jPassword))
            {
                response.Add(new JProperty("message", "Error: Password Not Sent"));
                return(response);
            }

            //Validate Domain
            String joinedDomain = "";

            try { joinedDomain = Domain.GetComputerDomain().Name; } catch { };

            String localDomain = System.Environment.MachineName;

            JToken jDomain;

            if (request.TryGetValue("domain", out jDomain))
            {
                if ((jDomain.ToString() != joinedDomain) && jDomain.ToString() != localDomain)
                {
                    response.Add(new JProperty("message", "Error: Domain Not Available"));
                    return(response);
                }
            }

            //User Authentication
            PrincipalContext pc;

            if ((jDomain == null) || (jDomain.ToString() == localDomain))
            {
                pc = new PrincipalContext(ContextType.Machine);
            }
            else
            {
                pc = new PrincipalContext(ContextType.Domain, joinedDomain);
            }


            if (!pc.ValidateCredentials(jUsername.ToString(), jPassword.ToString()))
            {
                response.Add(new JProperty("message", $"Login Failed"));
                return(response);
            }

            UserPrincipal user = UserPrincipal.FindByIdentity(pc, jUsername.ToString());

            PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

            //Check If has Administrate Rights
            bool hasAdminRights = false;

            foreach (Principal p in groups)
            {
                // make sure to add only group principals
                if (p is GroupPrincipal)
                {
                    if (p.Name == "Administrators")
                    {
                        hasAdminRights = true;
                    }
                }
            }

            if (!hasAdminRights)
            {
                response.Add(new JProperty("message", $"Login Failed. User is Not an Administrator"));
                return(response);
            }

            //Get API KEy
            String ErrorMsg;

            KeyDbManager.TokenResponse apiToken;
            if ((jDomain == null) || (jDomain.ToString() == localDomain))
            {
                apiToken = KeyDbManager.GetApiToken(localDomain + '\\' + user.SamAccountName, user.Sid.Value, out ErrorMsg);
            }
            else
            {
                apiToken = KeyDbManager.GetApiToken(joinedDomain + '\\' + user.SamAccountName, user.Sid.Value, out ErrorMsg);
            }


            if (ErrorMsg != null)
            {
                response.Add(new JProperty("message", $"Login Failed: {ErrorMsg}"));
                return(response);
            }


            response.Add(new JProperty("message", $"Login Success."));
            response.Add(new JProperty("apiToken", apiToken.apiToken));

            return(response);
        }
        public JObject EditController([NakedBody] String rawData)
        {
            //Try to Parse JObject
            JObject request;
            JObject response = new JObject();

            try
            {
                request = JObject.Parse(rawData);
            }
            catch
            {
                response["message"] = "Invalid JSON Format";
                return(response);
            }


            //Check Serial Number Format
            if (request["serial"] == null)
            {
                response["message"] = "Invalid Serial";
                return(response);
            }

            UInt16 serialNum;

            if (!UInt16.TryParse(request["serial"].Value <String>(), out serialNum))
            {
                response["message"] = "Invalid Serial";
                return(response);
            }

            //Check Names
            if (request["controllerName"] == null || request["controllerName"].Value <String>().Length <= 0)
            {
                response["message"] = "Invalid Controller Name";
                return(response);
            }
            if (request["door1Name"] == null || request["door1Name"].Value <String>().Length <= 0)
            {
                response["message"] = "Invalid Door 1 Name";
                return(response);
            }
            if (request["door2Name"] == null || request["door2Name"].Value <String>().Length <= 0)
            {
                response["message"] = "Invalid Door 2 Name";
                return(response);
            }
            if (request["door3Name"] == null || request["door3Name"].Value <String>().Length <= 0)
            {
                response["message"] = "Invalid Door 3 Name";
                return(response);
            }
            if (request["door4Name"] == null || request["door4Name"].Value <String>().Length <= 0)
            {
                response["message"] = "Invalid Door 4 Name";
                return(response);
            }


            String ErrorMsg;

            //Edit
            if (!KeyDbManager.EditController(request["controllerName"].Value <String>(), serialNum, request["door1Name"].Value <String>(), request["door2Name"].Value <String>(), request["door3Name"].Value <String>(), request["door4Name"].Value <String>(), out ErrorMsg))
            {
                //Add Failed
                response["message"] = ErrorMsg;
                return(response);
            }

            //Success Response
            response["message"]      = "Controller Edit Success";
            response["controllerSN"] = serialNum;
            return(response);
        }
Exemplo n.º 18
0
        public JObject ScanCards()
        {
            //Reset The Stopwatch
            lock (scanIdle)
            {
                if (scanIdle == null)
                {
                    scanIdle = new Stopwatch();
                }

                scanIdle.Restart();
            }

            //Startup the watch thread
            if (!watchActive)
            {
                watchActive = true;
                scanValid   = false;
                scanStart.Restart();

                Task t = new Task(() => {
                    //Get Controllers

                    String ErrorMsg;
                    List <KeyDbManager.ControllerInfo> dbControllers = KeyDbManager.ListControllers(out ErrorMsg);

                    //Scan Net For Active Controllers
                    List <WGToolKit.WGController> netControllers = WGToolKit.WGController.ScanNet(FreesideKeyService.Properties.Settings.Default.controllerPort);

                    //Start Watch
                    foreach (WGToolKit.WGController nc in netControllers)
                    {
                        nc.startWatch((Object sender, WGToolKit.ControllerRecord recvRecord) =>
                        {
                            Int32 cardID           = (Int32)recvRecord.cardID;
                            Int32 controllerSerial = ((WGToolKit.WGController)sender).Connection.ID;
                            Int32 doorIndex        = WGToolKit.WGTools.getDoorFromRecordStatus(recvRecord.cardID, recvRecord.statusByte);

                            String doorName  = KeyDbManager.LookupDoorName(controllerSerial, doorIndex, out ErrorMsg);
                            CardScanResult c = new CardScanResult(cardID, controllerSerial, doorIndex, doorName);

                            lock (scanResults)
                            {
                                if (!scanResults.Contains(c) && scanValid)
                                {
                                    scanResults.Add(c);
                                }
                            }
                        });
                    }



                    //Watch Started. Now Just Wait FOr Idle Timer TO expire and cleanup
                    while (true)
                    {
                        //Timer to burn first two seconds of entries (Stale).
                        if (!scanValid)
                        {
                            lock (scanStart)
                            {
                                if (scanStart.ElapsedMilliseconds > 2000)
                                {
                                    scanValid = true;
                                }
                            }
                        }

                        lock (scanIdle)
                        {
                            if (scanIdle.ElapsedMilliseconds > 10000)
                            {
                                //Stop Watch
                                foreach (WGToolKit.WGController nc in netControllers)
                                {
                                    nc.stopWatch();
                                }

                                //Clear Lists;
                                watchActive = false;
                                scanResults.Clear();
                            }
                        }

                        Thread.Sleep(10);
                    }
                });

                t.Start();
            }

            //Reset the scan Timer
            lock (scanIdle)
            {
                scanIdle.Restart();
            }

            //Return List Of collected REsults
            JObject result = new JObject();

            lock (scanResults)
            {
                result["scanResults"] = JToken.FromObject(scanResults);
                result["message"]     = $"Scan Results Found: {scanResults.Count}";
            }


            return(result);
        }