コード例 #1
0
ファイル: SecureRest.cs プロジェクト: Pryaxis/Restful
        protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms, IRequest request, IHttpContext context)
        {
            if (!cmd.RequiresToken)
            {
                return(base.ExecuteCommand(cmd, verbs, parms, request, context));
            }

            var token = parms["token"];

            if (token == null)
            {
                return new RestObject("401")
                       {
                           Error = "Not authorized. The specified API endpoint requires a token."
                       }
            }
            ;

            SecureRestCommand secureCmd = (SecureRestCommand)cmd;
            TokenData         tokenData;

            if (!Tokens.TryGetValue(token, out tokenData) && !AppTokens.TryGetValue(token, out tokenData))
            {
                return new RestObject("403")
                       {
                           Error = "Not authorized. The specified API endpoint requires a token, but the provided token was not valid."
                       }
            }
            ;

            Group userGroup = TShock.Groups.GetGroupByName(tokenData.UserGroupName);

            if (userGroup == null)
            {
                Tokens.Remove(token);

                return(new RestObject("403")
                {
                    Error = "Not authorized. The provided token became invalid due to group changes, please create a new token."
                });
            }

            if (secureCmd.Permissions.Length > 0 && secureCmd.Permissions.All(perm => !userGroup.HasPermission(perm)))
            {
                return(new RestObject("403")
                {
                    Error = string.Format("Not authorized. User \"{0}\" has no access to use the specified API endpoint.", tokenData.Username)
                });
            }

            //Main.rand being null can cause issues in command execution.
            //This should solve that
            if (Main.rand == null)
            {
                Main.rand = new Terraria.Utilities.UnifiedRandom();
            }

            object result = secureCmd.Execute(verbs, parms, tokenData, request, context);

            if (cmd.DoLog && TShock.Config.LogRest)
            {
                TShock.Utils.SendLogs(string.Format(
                                          "\"{0}\" requested REST endpoint: {1}", tokenData.Username, this.BuildRequestUri(cmd, verbs, parms, false)),
                                      Color.PaleVioletRed);
            }

            return(result);
        }
    }
}