Esempio n. 1
0
        public RESTReplyData put_ice_address(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                // Context.Log.Debug("{0} domains/ice_server_addr PUT. Body={1}", _logHeader, pReq.RequestBody);
                bodyIceServerPut isr           = pReq.RequestBodyObject <bodyIceServerPut>();
                string           includeAPIKey = isr.domain.api_key;
                if (VerifyDomainAccess(aDomain, pReq, includeAPIKey, out string oFailureReason))
                {
                    aDomain.IceServerAddr = isr.domain.ice_server_address;
                }
                else
                {
                    Context.Log.Error("{0} PUT domains/%/ice_server_address not authorized. DomainID={1}",
                                      _logHeader, domainID);
                    respBody.RespondFailure(oFailureReason);
                    replyData.Status = (int)HttpStatusCode.Unauthorized;
                }
            }
            else
            {
                respBody.RespondFailure("No such domain");
                replyData.Status = (int)HttpStatusCode.NotFound;
            }
            return(replyData);
        }
Esempio n. 2
0
        public RESTReplyData admin_domain_delete(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                if (aAccount.IsAdmin)
                {
                    string domainID = pArgs.Count == 1 ? pArgs[0] : null;
                    if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
                    {
                        Domains.Instance.RemoveDomain(aDomain);
                    }
                    else
                    {
                        respBody.RespondFailure("No such domain");
                    }
                }
                else
                {
                    respBody.RespondFailure("Requesting account is not an administrator");
                    replyData.Status = (int)HttpStatusCode.Unauthorized;
                }
            }
            else
            {
                respBody.RespondFailure("Authorization token not found");
                replyData.Status = (int)HttpStatusCode.Unauthorized;
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 3
0
        public RESTReplyData get_public_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            string username = pArgs.Count == 1 ? pArgs[0] : null;

            if (Accounts.Instance.TryGetAccountWithUsername(username, out AccountEntity aAccount))
            {
                respBody.Data = new bodyUserPublicKeyReply()
                {
                    public_key = aAccount.Public_Key,
                    username   = aAccount.Username,
                    accountid  = aAccount.AccountID
                };
            }
            else
            {
                Context.Log.Error("{0} GET fetch of user public key for unknown acct. SenderKey: {1}, Username: {2}",
                                  _logHeader, pReq.SenderKey, username);
                respBody.RespondFailure("Unknown username");
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 4
0
        public RESTReplyData get_domain(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity dobj))
            {
                respBody.Data = new bodyDomainResponse()
                {
                    domain = new bodyDomainReplyData()
                    {
                        id = domainID,
                        ice_server_address = dobj.GetIceServerAddr(),
                        name = dobj.PlaceName
                    }
                };
            }
            else
            {
                // return nothing!
                respBody.RespondFailure("No domain with that ID");
                respBody.ErrorData("domain", "there is no domain with that ID");

                replyData.Status = (int)HttpStatusCode.NotFound;
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 5
0
        public RESTReplyData put_ice_address(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                // Context.Log.Debug("{0} domains/ice_server_addr PUT. Body={1}", _logHeader, pReq.RequestBody);
                bodyIceServerPut isr           = pReq.RequestBodyObject <bodyIceServerPut>();
                string           includeAPIKey = isr.domain.api_key;
                if (String.IsNullOrEmpty(aDomain.API_Key) || includeAPIKey == aDomain.API_Key)
                {
                    aDomain.IceServerAddr = isr.domain.ice_server_address;
                }
                else
                {
                    respBody.RespondFailure();
                    replyData.Status = 401; // not authorized
                }
            }
            else
            {
                respBody.RespondFailure();
                replyData.Status = 404;
            }
            return(replyData);
        }
Esempio n. 6
0
        public RESTReplyData get_temporary_name(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();
            ResponseBody  respBody  = new ResponseBody();

            PersonNameGenerator png  = new PersonNameGenerator();
            PlaceNameGenerator  plng = new PlaceNameGenerator();

            DomainEntity newDomain = new DomainEntity()
            {
                PlaceName            = png.GenerateRandomFirstName() + "-" + plng.GenerateRandomPlaceName() + "-" + new Random().Next(500, 9000).ToString(),
                DomainID             = Guid.NewGuid().ToString(),
                IPAddrOfFirstContact = pReq.RemoteUser.ToString()
            };

            newDomain.API_Key = Tools.MD5Hash($":{newDomain.PlaceName}::{newDomain.DomainID}:{newDomain.IceServerAddr}");
            Domains.Instance.AddDomain(newDomain.DomainID, newDomain);

            respBody.Data = new bodyDomainResponse()
            {
                domain = new bodyDomainReplyData()
                {
                    id      = newDomain.DomainID,
                    name    = newDomain.PlaceName,
                    api_key = newDomain.API_Key
                }
            };
            replyData.Body = respBody;  // serializes JSON
            Context.Log.Debug("{0} Returning temporary domain: id={1}, name={2}",
                              _logHeader, newDomain.DomainID, newDomain.PlaceName);

            replyData.CustomOutputHeaders.Add("X-Rack-CORS", "miss; no-origin");
            replyData.CustomOutputHeaders.Add("Access-Control-Allow-Origin", "*");
            return(replyData);
        }
Esempio n. 7
0
        public RESTReplyData get_domains(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                PaginationInfo pagination = new PaginationInfo(pReq);

                respBody.Data = new bodyDomainsReply()
                {
                    domains = Domains.Instance.Enumerate(pagination).Select(dom =>
                    {
                        return(new bodyDomainInfo(dom));
                    }).ToArray()
                };
            }
            else
            {
                respBody.RespondFailure("Unauthorized");
                replyData.Status = (int)HttpStatusCode.Unauthorized;
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 8
0
        private void GetAccountLocationIfSpecified(AccountEntity pAccount, RESTRequestData pReq)
        {
            try
            {
                // The 'location' information is sent only when it changes
                JObject requestBodyJSON = pReq.RequestBodyJSON();
                if (requestBodyJSON.ContainsKey("location"))
                {
                    bodyUserHeartbeatLocation requestData = pReq.RequestBodyObject <bodyUserHeartbeatLocation>();

                    bodyHeartbeatLocationInfo loc = requestData.location;
                    pAccount.Location = new LocationInfo()
                    {
                        Connected      = loc.connected,
                        Path           = loc.path,
                        PlaceID        = loc.place_id,
                        DomainID       = loc.domain_id,
                        NetworkAddress = loc.network_address,
                        NetworkPort    = Int32.Parse(loc.network_port ?? "9400"),
                        NodeID         = loc.node_id,
                        Availability   = Enum.Parse <Discoverability>(loc.availability ?? "none", false)
                    };
                    pAccount.Updated();
                }
            }
            catch (Exception e)
            {
                Context.Log.Error("{0} GetAccountLocationIfSpecified: Exception parsing body of message. AccountID={1}. {2}",
                                  _logHeader, pAccount.AccountID, e);
                Context.Log.Error("{0} GetAccountLocationIfSpecified:     Body = {1}", _logHeader, pReq.RequestBody);
            }
        }
Esempio n. 9
0
        public RESTReplyData user_tokens(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info

            if (pReq.Queries.TryGetValue("for_domain_server", out string oForDomainServer))
            {
                if (Boolean.Parse(oForDomainServer))
                {
                    // Getting a token for a domain server
                    if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity oAccount))
                    {
                        AuthTokenInfo token = oAccount.CreateAccessToken(AuthTokenInfo.ScopeCode.domain);
                        // The domain/account association is permenant... expiration is far from now
                        token.TokenExpirationTime = new DateTime(2999, 12, 31);

                        replyData.SetBody($"<center><h2>Your domain's access token is: {token.Token}</h2></center>");
                        replyData.MIMEType = "text/html";
                    }
                    else
                    {
                        // If the user is not logged in, go to a page to login and set things up
                        replyData.Status = (int)HttpStatusCode.Found;
                        replyData.CustomOutputHeaders.Add("Location",
                                                          Context.Params.P <string>(AppParams.P_DOMAIN_TOKENGEN_URL));
                        replyData.MIMEType = "text/html";
                    }
                }
            }
            return(replyData);
        }
Esempio n. 10
0
 public RESTReplyData admin_post_accounts(RESTRequestData pReq, List <string> pArgs)
 {
     return(APITargetedAccountOperation(pReq, pArgs, (pRespBody, pSrcAcct, pTargetAcct) =>
     {
         try
         {
             JObject body = pReq.RequestBodyJSON();
             if (body.ContainsKey("accounts"))
             {
                 JObject acctInfo = (JObject)body["accounts"];
                 Tools.SetIfSpecified <string>(acctInfo, "username", ref pTargetAcct.Username);
                 Tools.SetIfSpecified <string>(acctInfo, "email", ref pTargetAcct.Email);
                 Tools.SetIfSpecified <string>(acctInfo, "public_key", ref pTargetAcct.Public_Key);
                 if (acctInfo.ContainsKey("images"))
                 {
                     JObject imageInfo = (JObject)acctInfo["images"];
                     if (pTargetAcct.Images == null)
                     {
                         pTargetAcct.Images = new UserImages();
                     }
                     Tools.SetIfSpecified <string>(imageInfo, "hero", ref pTargetAcct.Images.Hero);
                     Tools.SetIfSpecified <string>(imageInfo, "thumbnail", ref pTargetAcct.Images.Thumbnail);
                     Tools.SetIfSpecified <string>(imageInfo, "tiny", ref pTargetAcct.Images.Tiny);
                 }
             }
         }
         catch (Exception e)
         {
             Context.Log.Error("{0} POST /api/v1/account/%: exception parsing body '{1}' from {2} account {3}",
                               _logHeader, pReq.RequestBody, pReq.SenderKey, pSrcAcct.Username);
             pRespBody.RespondFailure("Exception parsing message body", e.ToString());
             pRespBody.ErrorData("error", "parse body failure");
         }
     }));
 }
Esempio n. 11
0
        public RESTReplyData user_create(RESTRequestData pReq, List <string> pArgs)
        {
            // This specific endpoint only creates a user
            users_request usreq;

            try
            {
                usreq = pReq.RequestBodyObject <users_request>();
            }
            catch (Exception e)
            {
                Context.Log.Error("{0} Malformed reception: {1}", _logHeader, e.ToString());
                throw new Exception("Malformed content");
            }

            string userName  = usreq.User["username"];
            string userPW    = usreq.User["password"];
            string userEmail = usreq.User["email"];

            ResponseBody respBody = new ResponseBody();

            if (!Users.Instance.CreateAccountPW(userName, userPW, userEmail))
            {
                // If didn't create, return a fail
                respBody = new ResponseBody("fail", new Dictionary <string, string>()
                {
                    { "username", "already exists" }
                });
            }

            return(new RESTReplyData(respBody));
        }
Esempio n. 12
0
        public RESTReplyData user_activity(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            try
            {
                bodyUserActivityRequest reqBody = pReq.RequestBodyObject <bodyUserActivityRequest>();

                if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
                {
                    // What does an activity do?
                    Context.Log.Info("{0} Received user_activity={1} from {2}",
                                     _logHeader, reqBody.action_name, aAccount.Username);
                }
                else
                {
                    Context.Log.Info("{0} Received user_activity={1} from unknown user",
                                     _logHeader, reqBody.action_name);
                    respBody.Status  = "notfound";
                    replyData.Status = (int)HttpStatusCode.NotFound;
                }
            }
            catch
            {
                Context.Log.Error("{0} Badly formed user_activities request from {1}",
                                  _logHeader, pReq.SenderKey);
                replyData.Status = (int)HttpStatusCode.BadRequest;
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 13
0
        public RESTReplyData Heartbeat(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData _reply = new RESTReplyData();

            Heartbeat_Memory mem = Heartbeat_Memory.GetHeartbeat();

            if (mem.Contains(pReq.RemoteUser.ToString()))
            {
                mem.Set(pReq.RemoteUser.ToString(), Guid.NewGuid().ToString());
            }
            else
            {
                mem.Add(pReq.RemoteUser.ToString(), Guid.NewGuid().ToString());
            }
            heartbeat_ReplyData hbrd = new heartbeat_ReplyData();

            hbrd.status = "success";
            hbrd.data   = new Dictionary <string, string>();
            hbrd.data.Add("session_id", mem.Get(pReq.RemoteUser.ToString()));
            _reply.Status = 200;
            _reply.Body   = JsonConvert.SerializeObject(hbrd);


            return(_reply);
        }
Esempio n. 14
0
        public RESTReplyData get_public_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                respBody.Data = new bodyDomainPublicKeyGetResponse()
                {
                    public_key = aDomain.Public_Key
                };
            }
            else
            {
                // return nothing!
                respBody.RespondFailure("unknown domain");
                respBody.ErrorData("domain", "there is no domain with that ID");    // legacy HiFi compatibility
                replyData.Status = (int)HttpStatusCode.NotFound;
                // Context.Log.Debug("{0} get_domain GET: no domain! Returning: {1}", _logHeader, replyData.Body);
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 15
0
        public RESTReplyData user_profile_gen(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                respBody.Data = new bodyUserProfileReply()
                {
                    user = new bodyUserProfileInfo()
                    {
                        username          = aAccount.Username,
                        accountid         = aAccount.AccountID,
                        xmpp_password     = aAccount.xmpp_password,
                        discourse_api_key = aAccount.discourse_api_key,
                        wallet_id         = aAccount.wallet_id
                    }
                };
            }
            else
            {
                Context.Log.Error("{0} GET user/profile requested without auth token. Token={1}", _logHeader, pReq.AuthToken);
                respBody.RespondFailure("Unauthorized");
            }
            replyData.SetBody(respBody, pReq);
            // Context.Log.Debug("{0} GET user/profile. Response={1}", _logHeader, replyData.Body);
            return(replyData);
        }
Esempio n. 16
0
        public RESTReplyData admin_get_accounts(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                PaginationInfo     pagination  = new PaginationInfo(pReq);
                AccountFilterInfo  acctFilter  = new AccountFilterInfo(pReq);
                AccountScopeFilter scopeFilter = new AccountScopeFilter(pReq, aAccount);

                respBody.Data = new bodyAccountsReply()
                {
                    accounts = Accounts.Instance.Enumerate(pagination, acctFilter, scopeFilter).Select(acct =>
                    {
                        return(new bodyAccountInfo(acct));
                    }).ToArray()
                };
            }
            else
            {
                Context.Log.Error("{0} GET accounts requested with bad auth", _logHeader);
                respBody.RespondFailure("Bad authorization");
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 17
0
        public RESTReplyData user_location_set(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                try
                {
                    GetAccountLocationIfSpecified(aAccount, pReq);
                }
                catch (Exception e)
                {
                    Context.Log.Error("{0} PUT user/location Failed body parsing. Acct={1}: {2}",
                                      _logHeader, aAccount.AccountID, e);
                    respBody.RespondFailure("failed location parsing", e.ToString());
                }
            }
            else
            {
                respBody.RespondFailure("Unauthorized");
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 18
0
        public RESTReplyData user_friends_post(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();

            if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity aAccount))
            {
                bodyUserFriendsPost body = pReq.RequestBodyObject <bodyUserFriendsPost>();
                string friendname        = body.username;
                Context.Log.Debug("{0} user_friends_post: adding friend {1} for user {2}",
                                  _logHeader, body.username, aAccount.Username);
                if (Accounts.Instance.TryGetAccountWithUsername(friendname, out AccountEntity _))
                {
                    if (!aAccount.Friends.Contains(friendname))
                    {
                        aAccount.Friends.Add(friendname);
                    }
                }
                else
                {
                    Context.Log.Error("{0} user_friends_post: attempt to add friend that does not exist. Requestor={1}, friend={2}",
                                      _logHeader, aAccount.Username, friendname);
                    respBody.RespondFailure("Attempt to add friend that does not exist");
                }
            }
            else
            {
                Context.Log.Error("{0} GET user/friends requested without auth token. Token={1}",
                                  _logHeader, pReq.AuthToken);
                respBody.RespondFailure("Unauthorized");
            }
            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 19
0
        public RESTReplyData get_public_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                respBody.Data = new bodyDomainPublicKeyGetResponse()
                {
                    public_key = aDomain.Public_Key
                };
            }
            else
            {
                // return nothing!
                respBody.RespondFailure();
                respBody.Data = new Dictionary <string, string>()
                {
                    { "domain", "there is no domain with that ID" }
                };
                replyData.Status = 404;
                // Context.Log.Debug("{0} get_domain GET: no domain! Returning: {1}", _logHeader, replyData.Body);
            }

            replyData.Body = respBody;  // serializes JSON
            return(replyData);
        }
Esempio n. 20
0
        /// <summary>
        /// A domain is either using an apikey (if not registered with a user account) or is
        /// using a user authtoken (if registered). This routine checks whether this
        /// domain request includes the right stuff for now.
        /// </summary>
        /// <param name="pDomain"></param>
        /// <param name="pReq"></param>
        /// <returns></returns>
        private bool VerifyDomainAccess(DomainEntity pDomain, RESTRequestData pReq, string pPossibleApiKey, out string oFailureReason)
        {
            bool   ret     = false;
            string failure = null;

            if (String.IsNullOrEmpty(pReq.AuthToken))
            {
                // No auth token. See if there is an APIKey and use that
                if (!String.IsNullOrEmpty(pDomain.API_Key))
                {
                    ret = pDomain.API_Key.Equals(pPossibleApiKey);
                    if (!ret)
                    {
                        failure = "API key does not match";
                    }
                }
            }
            else
            {
                // If the domain passed an auth token, get access with that
                if (Accounts.Instance.TryGetAccountWithAuthToken(pReq.AuthToken, out AccountEntity oAccount, AuthTokenInfo.ScopeCode.domain))
                {
                    // Make sure this domain and this account are working together
                    if (String.IsNullOrEmpty(pDomain.SponserAccountID))
                    {
                        // The domain doesn't have a sponser so assign
                        pDomain.SponserAccountID = oAccount.AccountID;
                        ret = true;
                    }
                    else
                    {
                        // There is a sponser for this domain. Make sure it stays the same
                        if (pDomain.SponserAccountID.Equals(oAccount.AccountID))
                        {
                            ret = true;
                        }
                        else
                        {
                            Context.Log.Error("{0} Domain used authtoken from different acct. DomainID={1}, SponserID={2}, newAcct={3}",
                                              _logHeader, pDomain.DomainID, pDomain.SponserAccountID, oAccount.AccountID);
                            ret     = false;
                            failure = "Domain auth token does not match with sponsering account";
                        };
                    };
                }
                ;
            };
            if (!ret)
            {
                Context.Log.Debug("{0} VerifyDomainAccess: failed auth. DomainID={1}, domain.apikey={2}, AuthToken={3}, apikey={4}",
                                  _logHeader, pDomain.DomainID, pDomain.API_Key, pReq.AuthToken, pPossibleApiKey);
                if (String.IsNullOrEmpty(failure))
                {
                    failure = "Unauthorized";
                }
            }
            oFailureReason = failure;
            return(ret);
        }
Esempio n. 21
0
        public RESTReplyData set_public_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                try
                {
                    string includedAPIKey = pReq.RequestBodyMultipart("api_key");

                    // If this is a temp domain, the supplied API key must match
                    // TODO: is there another Authorization later (ie, maybe user auth?)
                    if (String.IsNullOrEmpty(aDomain.API_Key) || aDomain.API_Key == includedAPIKey)
                    {
                        // The PUT sends the key as binary but it is later sent around
                        //    and processed as a Base64 string.
                        Stream byteStream = pReq.RequestBodyMultipartStream("public_key");
                        if (byteStream != null)
                        {
                            using var memStream = new MemoryStream();
                            byteStream.CopyTo(memStream);
                            aDomain.Public_Key = Convert.ToBase64String(memStream.ToArray());
                            aDomain.Updated();
                            // Context.Log.Debug("{0} successful set of public_key for {1}", _logHeader, domainID);
                        }
                        else
                        {
                            Context.Log.Error("{0} could not extract public key from request body: domain {1}",
                                              _logHeader, domainID);
                            replyData.Status = 401; // not authorized
                            respBody.RespondFailure();
                        }
                    }
                    else
                    {
                        Context.Log.Error("{0} attempt to set public_key with non-matching APIKeys: domain {1}",
                                          _logHeader, domainID);
                        replyData.Status = 401; // not authorized
                        respBody.RespondFailure();
                    }
                }
                catch (Exception e)
                {
                    Context.Log.Error("{0} exception parsing multi-part http: {1}", _logHeader, e.ToString());
                    respBody.RespondFailure();
                }
            }
            else
            {
                Context.Log.Error("{0} attempt to set public_key for unknown domain {1}", _logHeader, domainID);
                respBody.RespondFailure();
            }

            replyData.Body = respBody;
            return(replyData);
        }
Esempio n. 22
0
 public RESTReplyData admin_delete_accounts(RESTRequestData pReq, List <string> pArgs)
 {
     return(APITargetedAccountOperation(pReq, pArgs, (pRespBody, pSrcAcct, pTargetAcct) =>
     {
         Context.Log.Error("{0} UNIMPLIMENTED: DELETE /api/v1/account/%. From={1}",
                           _logHeader, pReq.SenderKey);
         pRespBody.RespondFailure("Not implemented");
     }));
 }
Esempio n. 23
0
        public RESTReplyData set_public_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            SessionEntity aSession = Sessions.Instance.UpdateSession(pReq.SenderKey);

            string domainID = pArgs.Count == 1 ? pArgs[0] : null;

            if (Domains.Instance.TryGetDomainWithID(domainID, out DomainEntity aDomain))
            {
                try
                {
                    string includedAPIKey = pReq.RequestBodyMultipart("api_key");
                    if (VerifyDomainAccess(aDomain, pReq, includedAPIKey, out string oFailureReason))
                    {
                        // The PUT sends the key as binary but it is later sent around
                        //    and processed as a Base64 string.
                        Stream byteStream = pReq.RequestBodyMultipartStream("public_key");
                        if (byteStream != null)
                        {
                            aDomain.Public_Key = Tools.ConvertPublicKeyStreamToBase64(byteStream);
                            aDomain.Updated();
                            // Context.Log.Debug("{0} successful set of public_key for {1}", _logHeader, domainID);
                        }
                        else
                        {
                            Context.Log.Error("{0} could not extract public key from request body: domain {1}",
                                              _logHeader, domainID);
                            replyData.Status = (int)HttpStatusCode.Unauthorized;
                            respBody.RespondFailure("Could not extract public key from request body");
                        }
                    }
                    else
                    {
                        Context.Log.Error("{0} attempt to set public_key when no authorized: domain {1}",
                                          _logHeader, domainID);
                        replyData.Status = (int)HttpStatusCode.Unauthorized;
                        respBody.RespondFailure(oFailureReason);
                    }
                }
                catch (Exception e)
                {
                    Context.Log.Error("{0} exception parsing multi-part http: {1}", _logHeader, e.ToString());
                    respBody.RespondFailure("Exception parsing multi-part http", e.ToString());
                }
            }
            else
            {
                Context.Log.Error("{0} attempt to set public_key for unknown domain {1}", _logHeader, domainID);
                respBody.RespondFailure("unknown domain");
            }

            replyData.SetBody(respBody, pReq);
            return(replyData);
        }
Esempio n. 24
0
        public RESTReplyData get_api_options(RESTRequestData pReq, List<string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info

            replyData.CustomOutputHeaders.Add("Access-Control-Allow-Origin", "*");
            replyData.CustomOutputHeaders.Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
            replyData.CustomOutputHeaders.Add("Access-Control-Allow-Headers", "Content-Type, " + RESTReplyData.ERROR_HEADER);

            return replyData;
        }
Esempio n. 25
0
        public RESTReplyData get_marketplace_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            respBody.Data = new bodyMarketplaceKeyResponse()
            {
                public_key = Context.Params.P <string>("Commerce.MarketplaceKey")
            };
            replyData.Body = respBody;  // serializes JSON

            return(replyData);
        }
Esempio n. 26
0
        public RESTReplyData get_marketplace_key(RESTRequestData pReq, List <string> pArgs)
        {
            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info
            ResponseBody  respBody  = new ResponseBody();   // The request's "data" response info

            respBody.Data = new bodyMarketplaceKeyResponse()
            {
                public_key = Context.Params.P <string>(AppParams.P_COMMERCE_MARKETPLACEKEY)
            };
            replyData.SetBody(respBody, pReq);

            return(replyData);
        }
Esempio n. 27
0
        public RESTReplyData user_locker_get(RESTRequestData pReq, List <string> pArgs)
        {
            ResponseBody respBody = new ResponseBody();

            if (Users.Instance.TryGetUserWithAuth(pReq.AuthToken, out UserEntity aUser))
            {
                // TODO: do whatever one does with a locker
            }
            else
            {
                respBody.Status = "fail";
            }
            return(new RESTReplyData(respBody));
        }
Esempio n. 28
0
        public RESTReplyData get_page(RESTRequestData pReq, List <string> pArgs)
        {
            Context.Log.Debug("{0} GET /static/: {1}", _logHeader, pReq.RawURL);
            string baseDir = Context.Params.P <string>(AppParams.P_STORAGE_STATIC_DIR);

            // If the global list of static filenames hasn't been built, build it
            lock (staticFilenames)
            {
                if (staticFilenames.Count == 0)
                {
                    AddToStaticFilenames(baseDir);
                }
            }

            RESTReplyData replyData = new RESTReplyData();  // The HTTP response info

            string afterString = String.Join(Path.DirectorySeparatorChar, pArgs);

            string filename = Path.Combine(baseDir, afterString);

            if (staticFilenames.Contains(filename.ToLower()))
            {
                if (File.Exists(filename))
                {
                    replyData.SetBody(File.ReadAllText(filename));
                    string exten    = Path.GetExtension(filename);
                    var    mimeType = exten switch
                    {
                        ".css" => "text/css",
                        ".json" => "text/json",
                        ".yaml" => "text/yaml",
                        ".html" => "text/html",
                        ".js" => "text/javascript",
                        _ => "text/text",
                    };
                    replyData.MIMEType = mimeType;
                }
                else
                {
                    Context.Log.Error("{0} File in static list but not in filesystem: {1}", _logHeader, filename);
                    replyData.Status = 401;
                }
            }
            else
            {
                Context.Log.Error("{0} Access to non-existant static file: {1}", _logHeader, filename);
                replyData.Status = 401;
            }
            return(replyData);
        }
Esempio n. 29
0
 public RESTReplyData account_get_tokens(RESTRequestData pReq, List <string> pArgs)
 {
     return(APITargetedAccountOperation(pReq, pArgs, (pRespBody, pSrcAcct, pTargetAcct) =>
     {
         PaginationInfo pagination = new PaginationInfo(pReq);
         pRespBody.Data = new bodyTokensReply()
         {
             tokens = pTargetAcct.AuthTokens.Enumerate(pagination).Select(tok =>
             {
                 return new bodyTokenInfo(tok);
             }).ToArray()
         };
     }));
 }
Esempio n. 30
0
 public RESTReplyData account_delete_tokens(RESTRequestData pReq, List <string> pArgs)
 {
     return(APITargetedAccountOperation(pReq, pArgs, (pRespBody, pSrcAcct, pTargetAcct) =>
     {
         string tokenId = pArgs.Count > 1 ? pArgs[1] : null;
         if (tokenId != null)
         {
             if (pTargetAcct.TryGetAuthTokenInfo(tokenId, out AuthTokenInfo tokenInfo))
             {
                 pTargetAcct.AuthTokens.Delete(tokenInfo);
             }
         }
     }));
 }